类的属性不限制属性

2024-05-16 04:12:50 发布

您现在位置:Python中文网/ 问答频道 /正文

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

Tags: selfreturnif属性defstatstypeposition
2条回答

另一个问题是hp.setter。第二个if语句应替换为elif,因为当hp小于0时,第一个if中的self.__hp被设置为0,然后在没有elif的情况下,它在else中被设置为负值:

@hp.setter
def hp(self, hp):
    if hp < 0:
        self.__hp = 0
    elif hp > self.maxhp:
        self.__hp = self.maxhp
    else:
        self.__hp = hp

__init__中,self.hp = self.maxhp行应该是self.__hp = self.maxhp。这样,它只在@property方法中设置/获取。你知道吗

处理postionxy的方式与处理hp的方式相同。在内部使用_postion_x_y来对应getter和setter中的值;并在每个getter和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

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

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

相关问题 更多 >