Python getter赋予AttributeError对象没有属性

时间:2017-10-16 20:57:13

标签: python oop encapsulation python-3.6

我必须使用Python的setter部分,我认为我理解但我想我没有。我试图改变对象的参数,我一直在与初始化和东西中的声明搏斗,但我似乎没有得到它。 Python给了我错误

Traceback (most recent call last):
  File "C:\Users\mkrui\workspace\YiviY\yiviy.py", line 71, in <module>
frits.position['x'] += random.randint(-15,15) #make object
  File "C:\Users\mkrui\workspace\YiviY\yiviy.py", line 45, in position
return self._position
AttributeError: 'lifeform' object has no attribute '_position'

代码:

class lifeform(object):
    kind = "lifeform"
    def __init__(self, max_age = (100), speed = (50), sati = (80), max_sati = (100), position = {'x': random.randint(0,WIDE), 'y': random.randint(0,HIGH)}):
        self.age = 0
        self.max_age = max_age
        self.speed = speed
        self.strength = 100 - speed
        self.sati = sati
        self.max_hunger = max_sati
        self.size = 10
        self.color = [155,155,255]
        self.position = position

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

    @position.setter
    def position(self, pos):
        if pos['x'] > WIDE:
            self._position['x'] = WIDE - 20
        elif pos['x'] <0:
            self._position['x'] = 20
        if pos['y'] > HIGH:
            self._position['y'] = HIGH - 20
        elif pos['y'] <0:
            self._position['y'] = 20

0 个答案:

没有答案