【问题标题】:Unexpected behavior when properties is used over getters and setters in python 2.7 [duplicate]python 2.7中在getter和setter上使用属性时的意外行为[重复]
【发布时间】: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


    【解决方案1】:

    这是Python property decorator not working, why? 的副本 在 Python 2 中,您需要从 object 继承才能获得与 Python 3 相同的行为,否则您仍然处于老式类的土地上。

    【讨论】:

    • 谢谢这解决了我的问题
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-05-03
    相关资源
    最近更新 更多