2

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?

Daniel Li
  • 123
  • 11

2 Answers2

4

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")
Padraic Cunningham
  • 176,452
  • 29
  • 245
  • 321
0

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.

Community
  • 1
  • 1
Celeo
  • 5,583
  • 8
  • 39
  • 41