Skip to main content
 首页 » 编程设计

Python:用属性覆盖成员

2025年05月04日16qq号

我试图用一个属性覆盖 Python (2.7) 类的成员,如以下代码所示:

class Base: 
    def __init__(self): 
        self.foo = 1 
 
class Derived(Base): 
    foo = property(lambda self: 2) 
 
print Derived().foo 

但是,最后一行打印的是 1 而不是 2。从​​我认为属性应该起作用的方式(即,稍后可以轻松地将成员更改为函数)来看,这对我来说似乎违反直觉。我错过了什么吗?有什么解决方法吗?

请您参考如下方法:

这不起作用,因为您没有使用新式类。属性是仅适用于新型类的描述符。你的代码是这样的:

您创建了一个类Derived,其类属性为foo。然后,当您创建该类的实例时,Base.__init__ 接管,因为 Derived 没有 __init__ 并且您添加了实例属性 foo 优先于类属性。

如果你改变:

class Base: #old style class 

到:

class Base(object):  #new style class 

你会遇到一个全新的问题,主要是你的属性没有适当定义的 setter,所以当你在 self.foo = 1 Base.__init__ 你会得到一个AttributeError