1

我有这个带有距离属性的 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") 方法中都有打印语句,但是当我获取或设置距离时,我们从未在输出中看到:

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 运行的。

4

1 回答 1

5

property仅适用于新式类。您需要通过这样声明它来创建RoomPlaceholder一个子类:object

class RoomPlaceholder(object):
    # etc.
于 2013-10-30T21:21:17.310 回答