【发布时间】:2019-03-11 16:14:21
【问题描述】:
我在 getter 和 setter 上尝试了属性,如下面的代码所示,当调用 B 类测试函数时,我预计会调用 A 类 setter,但不幸的是创建了 B 类的新实例变量。在 python 2.7.13 中观察到了这种行为,并且在 python 3 中可以正常工作。
代码:
class A:
def __init__(self):
self.a = 10
@property
def vala(self):
print ("Into Vala getter")
return self.a
@vala.setter
def vala(self, a):
print ("Into Vala setter")
self.a = a
class B:
def test(self):
self.a = A()
self.a.vala = 10
print ("B.test completed")
b = B()
b.test()
使用 python 2.7.13 输出
B.test completed
使用 python 3 输出
Into Vala setter
B.test completed
我的问题是,如果这是预期的行为,如何在 python 2.7 中使用组合?
【问题讨论】:
标签: python-2.7 python-decorators