Python 对象@property
我正在尝试创建一个点类,它定义一个名为“坐标”的属性。然而,它的行为并不像我预期的那样,我不明白为什么。
class Point:
def __init__(self, coord=None):
self.x = coord[0]
self.y = coord[1]
@property
def coordinate(self):
return (self.x, self.y)
@coordinate.setter
def coordinate(self, value):
self.x = value[0]
self.y = value[1]
p = Point((0,0))
p.coordinate = (1,2)
>>> p.x
0
>>> p.y
0
>>> p.coordinate
(1, 2)
似乎 px 和 py 由于某种原因没有被设置,即使设置器“应该”设置这些值。有人知道这是为什么吗?
I'm trying to create a point class which defines a property called "coordinate". However, it's not behaving like I'd expect and I can't figure out why.
class Point:
def __init__(self, coord=None):
self.x = coord[0]
self.y = coord[1]
@property
def coordinate(self):
return (self.x, self.y)
@coordinate.setter
def coordinate(self, value):
self.x = value[0]
self.y = value[1]
p = Point((0,0))
p.coordinate = (1,2)
>>> p.x
0
>>> p.y
0
>>> p.coordinate
(1, 2)
It seems that p.x and p.y are not getting set for some reason, even though the setter "should" set those values. Anybody know why this is?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
property
方法(以及扩展后的@property
装饰器)需要一个新式类,即一个object
的子类。例如,
应该是
另外,Python 2.6 中添加了
setter
属性(以及其他属性)。The
property
method (and by extension, the@property
decorator) requires a new-style class i.e. a class that subclassesobject
.For instance,
should be
Also, the
setter
attribute (along with the others) was added in Python 2.6.如果您从对象派生 Point ,它将起作用:
It will work if you derive Point from object: