[英]Python property being ignored, acting like an attribute
I've got this RoomPlaceholder class with a distance property; 我有一个带有distance属性的RoomPlaceholder类; when you set the distance property, it should automatically calculate what the x and y of the class should be, based on a random angle and the distance.
设置distance属性时,它应根据随机角度和距离自动计算类的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
However, it's not working. 但是,它不起作用。 Based on the output from the console, it looks like it's treating distance as an attribute rather than a property;
根据控制台的输出,看起来好像将距离视为属性而不是属性。 note that I've got print statements in both the getter ("gamma") and setter ("delta") methods, but we never see either in the output when I get or set the distance:
请注意,我在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]
I'm using Python 2.7, and this is being run via Sublime Text 3 in Windows 7. 我正在使用Python 2.7,并且正在Windows 7中通过Sublime Text 3运行它。
property
only works for new-style classes . property
仅适用于新型类 。 You need to make RoomPlaceholder
a subclass of object
by declaring it thusly: 您需要通过这样声明,使
RoomPlaceholder
成为object
的子类:
class RoomPlaceholder(object):
# etc.
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.