在 python 2.7 中对 getter 和 setter 使用属性时出现意外行为



我尝试了对 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 属性装饰器不起作用的副本,为什么? 在 Python 2 中,你需要从对象继承才能获得与 Python 3 相同的行为,否则你仍然处于旧式类土地上。

最新更新