属性 setter 当属性以“__”开头时不起作用?

Property setter not working when attribute starts with "__"?

我正在使用 Python 3.8.6,这很好用

class A:
    @property
    def _a(self):
        return getattr(self, '_a_', 0)

    @_a.setter
    def _a(self, value):
        self._a_ = value


a = A()
print(a._a)  # prints 0
a._a = 10
print(a._a)  # prints 10 as expected

这行不通

class A:
    @property
    def _a(self):
        return getattr(self, '__a', 0)

    @_a.setter
    def _a(self, value):
        self.__a = value

a = A()
print(a._a)  # prints 0
a._a = 10
print(a._a)  # prints 0 again

这太令人兴奋了!第一个和第二个示例之间的唯一区别是私有属性是 __a 而不是 _a_

知道为什么吗?我没弄清楚

这是由于 private name mangling,但它不适用于字符串文字的内容,例如您传递给 getattr() 的内容。

幸运的是修复很简单:

class A:
    @property
    def _a(self):
        return getattr(self, '_A__a', 0)

    @_a.setter
    def _a(self, value):
        self.__a = value

a = A()
print(a._a)  # prints 0
a._a = 10
print(a._a)  # prints 10 now