Skip to main content
 首页 » 编程设计

Python在继承时使用带有super的类属性

2025年02月15日12JeffreyZhao

我有一段python代码:

class A(object): 
    args = [1,2] 
    def __init__(self): 
        print self.args 
 
class B(A): 
    args = [3,4] 
    def __init__(self): 
        super(B, self).__init__() 
        print self.args 
 
B() 

输出是:

[3, 4]

[3, 4]

不是

[1,2]

[3,4]

为什么从派生类调用基类的构造函数时,使用的类属性来自派生类的命名空间?有没有办法让我使用函数所在类的类属性?

请您参考如下方法:

Is there a way for me to use the class attributes of the class in which the function resides in?

是的。通过它们的类属性名称而不是它们的实例属性名称来引用它们。即 A.args,而不是 self.args。

class A(object): 
    args = [1,2] 
    def __init__(self): 
        print A.args