简体   繁体   中英

Changing attributes of an object in a python class

So, my question is, if I were to make a Race based on this class, say, an elf. I make the elf like this: elf = Race('Elf', 100, 50, 60, 90)

If the elf got into combat, how do I make his health go down in that one instance, or any of his other stats go up based on a bonus of some sort, like if he had some kind of equipment giving him +(stat)?

Kind of a specific question, I know.

Here is the class Race I have set up so far. . .

class Race(object):

race = None
health = None
strength = None
speed = None 
endurance = None


def __init__(self, race, health, strength, speed, endurance):
    self.race = race
    self.health = health
    self.strength = strength
    self.speed = speed
    self.endurance = endurance


def set_race(self, race):
    self.race = race

def set_health(self, health):
    self.health = health

def set_strength(self, strength):
    self.strength = strength

def set_speed(self, speed):
    self.speed = speed

def set_endurance(self, endurance):
    self.endurance = endurance

Criticism is welcome, so long as its constructive!

Well, for one, the code wouldn't compile due to IndentationError but that's besides the point I suppose (so, please indent with 4 SPACES, not tab as per PEP-8 for each function body and class body).

With that said, you don't need any getters or setters because it's not pythonic. If you want to change the attribute of an object, just change the attribute. If you need to control how an attribute is set, then use properties .

Also, in your code below, you are actually not setting instance variables , you are setting member variables (please keep in mind I fixed the indentation):

class Race(object):

    race = None
    health = None
    strength = None
    speed = None 
    endurance = None

If you were to remove the above attributes but kept all the self.* in the __init__() function, you would then have instance attributes. The term self.* is stating "this is an attribute of myself, of my exact instance of me".

Also, please consider renaming race. You want a class to encapsulate all the attributes of an object. Think about it: a character's race doesn't have a health. A character can have a health, but the character also has a race. Both of these things are attributes of the character. I would suggest naming this class to class Character(object): .

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM