【发布时间】:2016-03-31 09:44:16
【问题描述】:
所以我创建了一个类并希望该属性 hp 始终保持在 0 和 maxhp 之间 从理论上讲,使 hp 成为一个属性应该会给我希望的结果:但不知何故它不起作用。
有没有办法来回链接属性?所以我已经存储了单元类对象的位置。在 2 个地方,一个属性位置包含一个 [x,y] 数组,另一个时间它存储在 2 个属性 x 和 y 中,每个属性都包含一个 int。 更改 self.x 或 self.y 应该会更改 self.position ,反之亦然。
class units(object):
def __init__(self,typus, position, stats):
self.type = typus
#they should be linked both directions
self.position = position
self.x = self.position[0]
self.y = self.position[1]
self.attack = stats[0]
self.defense = stats[1]
self.maxhp = stats[2]
self.hp = self.maxhp
def __repr__(self):
text = "This a %s at position [%s,%s].\n Attack: %s \n Defense: %s \n Hp : %s/%s \n " \
% (self.type,self.position[0],self.position[1], self.attack, self.defense, self.hp, self.maxhp)
return text
# hp set to always be in between 0 and maxhp
@property
def hp(self):
return self.__hp
@hp.setter
def hp(self, hp):
if hp < 0:
self.__hp = 0
if hp > self.maxhp:
self.__hp = self.maxhp
else:
self.__hp = hp
def takedmg(self,dmg):
self.hp -= max(dmg-self.defense, 0)
if self.hp <= 0:
self.alive = False
return self.hp
p = units("peasant", [1,1], [2,0,30])
p.takedmg(100)
print (p.hp) # it should be 0!
【问题讨论】:
-
除了我的回答中给出的更改外,请考虑使用
str.format()来表示长__repr__。
标签: python class python-3.x attributes