所以我创建了一个类,希望属性hp始终保持在0和maxhp之间 从理论上讲,让惠普成为一家房地产公司应该会给我一个预期的结果:但不知何故,它不起作用。你知道吗
有没有办法将属性前后链接?所以我存储了unit类对象的位置。在两个位置,一次是包含[x,y]数组的属性位置,另一次是它存储在两个属性x和y中,每个属性都包含一个int。 改变self.x或self.y应该改变自我定位另一方面也是。你知道吗
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!
另一个问题是
hp.setter
。第二个if
语句应替换为elif
,因为当hp
小于0时,第一个if
中的self.__hp
被设置为0,然后在没有elif
的情况下,它在else
中被设置为负值:在
__init__
中,self.hp = self.maxhp
行应该是self.__hp = self.maxhp
。这样,它只在@property
方法中设置/获取。你知道吗处理
postion
、x
和y
的方式与处理hp
的方式相同。在内部使用_postion
、_x
和_y
来对应getter和setter中的值;并在每个getter和setter中设置所有_prop
值。以position
为例:同样地,对于
x
和y
,尽管我认为您应该只通过position
来完成:顺便说一句,
hp
setter可以重写如下:相关问题 更多 >
编程相关推荐