Python属性被忽略,就像属性一样

时间:2013-10-30 21:19:09

标签: python properties

我的RoomPlaceholder类有一个距离属性;当你设置距离属性时,它应该根据随机角度和距离自动计算出类的x和y应该是什么。

class RoomPlaceholder:
    def __init__(self, width, height):
        self.width = width
        self.height = height
        self.id = ''.join(random.choice(string.ascii_uppercase + string.digits) for x in range(8))
        self.angle = Util.getRandomAngle() # = random.random() * math.pi * 2
        self.distance = 0

    @property
    def distance(self):
        print "gamma"
        return self._distance
    @distance.setter
    def distance(self, value):
        print "delta"
        self._distance = value
        coords = Util.getXYByDist(value, self.angle) # translates angle and distance into integer (x, y)
        print coords
        self._x = coords[0]
        self._y = coords[1]

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

    def __repr__(self):
        return "%s: [%sx%s] @ (%s, %s) Distance: %s. Angle: %s." % (self.id, self.width, self.height, self.x, self.y, self.distance, self.angle)

if __name__ == "__main__":
    room = RoomPlaceholder(5,5)
    print "%s\n" % room.distance
    room.distance = 10
    print "%s\n" % room.distance
    print room
    pass

然而,它不起作用。根据控制台的输出,看起来它将距离视为属性而不是属性;请注意,我在getter(“gamma”)和setter(“delta”)方法中都有print语句,但是当我得到或设置距离时,我们从未在输出中看到:

Traceback (most recent call last):0

  File "D:\Dropbox\Programming\Python\DungeonGenerator\NewDungeonGenerator.py", line 142, in <module>

10

    print room
  File "D:\Dropbox\Programming\Python\DungeonGenerator\NewDungeonGenerator.py", line 132, in __repr__
    return "%s: [%sx%s] @ (%s, %s) Distance: %s. Angle: %s." % (self.id, self.width, self.height, self.x, self.y, self.distance, self.angle)
  File "D:\Dropbox\Programming\Python\DungeonGenerator\NewDungeonGenerator.py", line 97, in x
    return self._x
AttributeError: RoomPlaceholder instance has no attribute '_x'
[Finished in 0.0s]

我正在使用Python 2.7,这是通过Windows 7中的Sublime Text 3运行的。

1 个答案:

答案 0 :(得分:5)

property仅适用于new-style classes。您需要通过声明RoomPlaceholder使object成为class RoomPlaceholder(object): # etc. 的子类:

{{1}}