Steve.Gao
Steve.Gao

Reputation: 297

Use __init__ to set attribute

I'm trying pygame for a simple game. I want to have a class Player so that I can simply make a second or third player.

I want the player to have some attribute like HP. So my code is

class Player():
    HP=100
    Speed=5
    ICON=pygame.image.load('somepic.ipg')

But later I want players to have different icons or HP so I tried

class Player():

    def __init__(self,HP,ICON):
    self.HP=HP
    self.ICON=ICON

My code was like:

P1=Player(80,someicon) 
P1.HP=P1.HP-damage

and something like this. But then I got

AttributeError P1 doesn't have attribute.HP

I read the doc of __init__ but I don't understand why it's not working. I know I can use:

P1=Player()
P1.HP=80
P1.ICON=someicon

But I want to know more about class and __init__.

Upvotes: 0

Views: 197

Answers (1)

LhasaDad
LhasaDad

Reputation: 2143

In your init method you have not indented the lines under the function def. The self.* assignments should be indented further.

Upvotes: 2

Related Questions