属性 getter/setter 在 Python 2 中不起作用
我对 python 中的属性有点困惑。考虑下面的代码
class A:
@property
def N(self):
print("A getter")
return self._N
@N.setter
def N(self,v):
print("A setter")
self._N = v
def __init__(self):
self._N = 1
class B:
@property
def N(self):
print("B getter")
return self.a.N
@N.setter
def N(self,v):
print("B setter")
self.a.N = v
def __init__(self):
self.a = A()
if __name__ == '__main__':
b=B()
b.N = 2
print(b.N, b.a.N)
b.N = 3
print(b.N, b.a.N)
B 应该类似于 A 的包装器。它使用 getter 和 setter 将 A 的属性映射到自身(当然也可以通过继承来完成)。 问题是,它在 python2.6 中无法按预期工作,而在 python3 中却可以:
> python2 test.py
A getter
(2, 1)
A getter
(3, 1)
> python3 test.py
B setter
A setter
B getter
A getter
A getter
2 2
B setter
A setter
B getter
A getter
A getter
3 3
我做错了什么或者问题到底出在哪里?
I'm a bit confused about properties in python. Consider the following code
class A:
@property
def N(self):
print("A getter")
return self._N
@N.setter
def N(self,v):
print("A setter")
self._N = v
def __init__(self):
self._N = 1
class B:
@property
def N(self):
print("B getter")
return self.a.N
@N.setter
def N(self,v):
print("B setter")
self.a.N = v
def __init__(self):
self.a = A()
if __name__ == '__main__':
b=B()
b.N = 2
print(b.N, b.a.N)
b.N = 3
print(b.N, b.a.N)
B should be something like a wrapper for A. It uses getters and setters to map A's properties on itself (of course one could also do it via inheritance).
The problem is, that it simply doesn't work as expected in python2.6 while it does in python3:
> python2 test.py
A getter
(2, 1)
A getter
(3, 1)
> python3 test.py
B setter
A setter
B getter
A getter
A getter
2 2
B setter
A setter
B getter
A getter
A getter
3 3
Am I doing anything wrong or where exactly is the problem?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
A和B必须是Python 2.x中的新式类。
property([fget[, fset[, fdel[, doc]]]])< /代码>
因此,如果您从
object
派生,您的代码将按预期工作。
A and B must be new-style classes in Python 2.x.
property([fget[, fset[, fdel[, doc]]]])
So if you'll derive from
object
Your code will work as expected.