类的属性不限制属性

时间:2016-03-31 09:44:16

标签: python class python-3.x attributes

所以我创建了一个类并希望,该属性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!

2 个答案:

答案 0 :(得分:1)

另一个问题出在hp.setter。第二个if语句应替换为elif,因为当hp小于0时,self.__hp在第一个if中设置为0,然后,不{ {1}},在elif

中将其设置为负值
else

答案 1 :(得分:0)

__init__self.hp = self.maxhp行应为self.__hp = self.maxhp。这样,它只能在@property方法中设置/获取。

您将按照与postion相同的方式处理xyhp。在内部使用_postion_x_y来对应getter和setter中的值;并在每个的setter中设置所有_prop值。以position为例:

@property
def position(self):
    return self._position

@position.setter
def position(self, position):
    self._position = position  # do checking before this if needed
    self._x = position[0]
    self._y = position[1]

同样适用于xy,但我认为您应该只通过position执行此操作:

@property
def x(self):
    return self._x

@x.setter
def x(self, x):
    self._x = x
    # self._y remains unchanged
    self._position[0] = x

顺便说一句,hp setter可以重写如下:

@hp.setter
def hp(self, hp):
    self.__hp = max(0, min(hp, self.maxhp))