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

标签 python class inheritance class-attributes

我有一段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

关于Python在继承时使用带有super的类属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41192645/

相关文章:

python - 具有完整性要求的按频率分类的 Pandas Grouper

c++ - 哪种设计模式适合这种情况?

具有相同变量名的 Scala 类继承

java - 如何声明一个抽象方法,使参数类型(类)始终是Children类?

派生类中构造函数和析构函数的 C++ LNK2019 错误

python - 如何在Python中绘制圆柱体周围流线流的流线图?

python - 新的正则表达式模块模糊函数错误值。 Python

class - 当 setState 与类的对象实例发生 react 时会发生什么

c++ - 虚方法,operator=(), operator<<();

python - 如何让 Python 在现有的 NetBeans 中运行?