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