【问题标题】:python @property not overwrite class attribute [duplicate]python @property不覆盖类属性[重复]
【发布时间】:2016-10-19 10:27:51
【问题描述】:

我对 class 属性感到困惑。我知道Python解释器会首先在cls.__dict_(对象属性)中搜索attr,如果该属性不存在,它将查找类属性。但在那种情况下,我不知道为什么下面的结果返回 None

class A(object):
    __attr = None

    @property
    def attr(self):
        return self.__attr

class B(A):
    __attr = 1

c = B()
print(c.attr)
# None

【问题讨论】:

    标签: python oop


    【解决方案1】:

    这不是关于property,而是关于以__ 为前缀的属性的行为。这会触发名称修改,这几乎不是您想要的,并且在继承场景中会出现意外行为。不要使用它。

    【讨论】:

      猜你喜欢
      • 2015-09-30
      • 2018-06-22
      • 1970-01-01
      • 1970-01-01
      • 2016-07-20
      • 2016-11-13
      • 2014-04-30
      • 1970-01-01
      • 2013-01-19
      相关资源
      最近更新 更多