gpt4 book ai didi

Python 属性被忽略,表现得像一个属性

转载 作者:太空宇宙 更新时间:2023-11-04 09:06:55 24 4
gpt4 key购买 nike

我有一个带有距离属性的 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 运行的。

最佳答案

property仅适用于 new-style classes .您需要通过如下声明使 RoomPlaceholder 成为 object 的子类:

class RoomPlaceholder(object):
# etc.

关于Python 属性被忽略,表现得像一个属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19693993/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com