In Python, I was trying to make a character using a class with a random integer as a health value, but the result is the same every time.
class Player():
life = randint(25,30)
maxhealth = life
attack = 5
name = ""
......
The method I create the players with is like this:
playernum = -1
while playernum < 1:
playernum = int(input("How many players? "))
players = []
for x in range(playernum):
print("Player " + str(x+1))
players.append(Player())
How do I change it so that the health value is different for each player I create?
You should be using instance attributes:
class Player():
def __init__(self):
self.life = randint(25,30)
self.maxhealth = self.life
self.attack = 5
self.name = ""
You currently have class attributes which are only evaluated once. Add a print inside your class and you will see "here"
only appear once:
class Player():
print("here")
life = randint(25,30)
maxhealth = life
attack = 5
name = ""
If you do the same inside the init method you will see the print each time you create an instance:
class Player():
def __init__(self):
print("here")
With __init__
:
class Player():
def __init__(self):
self.life = randint(25,30)
self.maxhealth = life
self.attack = 5
self.name = ""
......
See also this question and its answers .
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.