问题
i'm trying to create a function to raise max hp whenever a stat is increased or decreased. i have tried changing self.maxHpCalc() player.** moving the variables = (int) into the orc class in every why i can think of and have been having no luck. depending on how i change it i get self/player have no attribute strength, maxHp or maxHpCalc is not defined.
class player:
def __init__(self, hp = 1 , maxHp = 1, strength = 4, defense = 5):
self.hp = hp
self.maxHp = maxHpCalc()
self.strength = strength
self.defense = defense
def maxHpCalc():
player.maxHp = player.strength + player.defense
class orc(player):
def __init__(self, hp, maxHp, strength , defnese):
super().__init__(hp, maxHp, strength, defense)
print(player.maxHp)
everything i change give me player/self has no attribute strength at the moment
回答1:
Here's some fixed code, with a small driver program to exercise the classes.
Note the following changes
- The function
maxHpCalcshould be a bound method, if it is to operate on data contained in aplayerinstance. Therefore it should have aselfparameter and should referencestrengthanddefensefrom that self reference. - When calling
_maxHpCalcyou should referenceself. I made it a bound method and it needs an instance to work on. I added an underscore to indicate it's a private method. - You should call
maxHpCalcafter setting the values ofstrengthanddefense, otherwise they are not defined at the point the function is called. player.maxHpmakes no sense.playeris a class and has no static propertymaxHp, you need an instance to access that property. I create an instance and reference that.
code:
class player:
def __init__(self, hp=1, maxHp=1, strength=4, defense=5):
self.hp = hp
self.strength = strength
self.defense = defense
self.maxHp = self._maxHpCalc()
def _maxHpCalc(self):
return self.strength + self.defense
class orc(player):
def __init__(self, hp, maxHp, strength , defense):
super().__init__(hp, maxHp, strength, defense)
p = player()
o = orc(1,2,3,4)
print(p.maxHp)
print(o.maxHp)
I also have to ask, why include a constructor parameter maxHp if you don't use it but calculate it from other parameters?
来源:https://stackoverflow.com/questions/43482829/working-on-classes-for-a-text-based-game-in-python