2013-10-30 65 views
1

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

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 

但是,它不工作。基于控制台的输出,它看起来像把距离视为属性而不是属性;请注意,我有两个吸气打印报表(“伽玛”)和setter(“增量”)的方法,但我们从来没有看到无论是在输出的时候,我得到或设置距离:

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

回答

5

property只适用于new-style classes。你需要通过如此宣称它做RoomPlaceholderobject一个子类:

class RoomPlaceholder(object): 
    # etc. 
+0

我使用性质别处没有困难,没有使用定义的那种类型的。例如,请参阅https://github.com/Asmor/python-roguelike/blob/master/Level.py#L43它为什么会在那里工作,但不在这里?编辑:澄清,您的解决方案确实工作;我只是困惑,为什么我以前没有遇到这个问题 – Asmor

+0

@Asmor:你以前是否仅仅在Python 3中工作?在Py3中,所有的类都是新的类型,而'(object)'是多余的,而在Python 2中,需要'(object)'来获得'property' * et alii *的功能。 – jwodder

+0

我确实在py3中启动了这个项目,但我已经切换到了py2。经过进一步的检查,我提到的那条线实际上并没有正常工作,但其失败并不明显。再次感谢! – Asmor