文档说:
Python supports a form of multiple inheritance as well. A class
definition with multiple base classes looks like this:
class DerivedClassName(Base1, Base2, Base3):
<statement-1>
.
.
.
<statement-N>
For most purposes, in the simplest cases, you can think of the search
for attributes inherited from a parent class as depth-first, left-to-
right, not searching twice in the same class where there is an overlap
in the hierarchy. Thus, if an attribute is not found in
DerivedClassName, it is searched for in Base1, then (recursively) in
the base classes of Base1, and if it was not found there, it was
searched for in Base2, and so on.
所以,我有以下代码对其进行测试:
class Class1:
c1_1 = 1.1
class Class2:
c2_1 = 2.1
class Blob(Class1, Class2):
def dump():
print('c1_1 = ' + str(c1_1))
Blob.dump()
但是,我明白了:
Traceback (most recent call last):
File "classinherit.py", line 13, in <module>
Blob.dump()
File "classinherit.py", line 11, in dump
print('c_1.1 = ' + str(c1_1))
NameError: name 'c1_1' is not defined
文档似乎说Python首先会在类Blob的范围内寻找一个(在这种情况下为类范围内的)变量,而没有找到它会搜索Class1和Class2类……但这显然没有发生。 / p>
有什么作用?
答案 0 :(得分:1)
如果要访问类变量,则必须以某种方式引用该类:
class Class1:
c1_1 = 1.1
class Class2:
c2_1 = 2.1
class Blob(Class1, Class2):
@classmethod
def dump(cls):
print('c1_1 = ' + str(cls.c1_1))
Blob.dump()
为了清楚起见,您必须始终引用类 ,而不仅仅是在继承的情况下。
例如,以下将不起作用:
class Klass():
v1 = 1
def dump():
print('class var = ' + str(v1))
Klass.dump()
NameError:名称'v1'未定义
同样,您必须引用该类才能使其起作用:
class Klass():
v1 = 1
@classmethod
def dump(cls):
print('class var = ' + str(cls.v1))
Klass.dump()
如果您不想使用@classmethod
,也可以执行以下操作:
class Klass():
v1 = 1
def dump():
print('class var = ' + str(Klass.v1))
Klass.dump()
但是请记住,更改类Klass
的名称也将需要更改Klass.v1
。
答案 1 :(得分:1)
您正在做的是您尝试访问类变量和(或)属性,而没有实际告诉它属于哪个类或没有引用该类。 您可以查看@Mike Scotty的答案,也可以正确地调用类变量,然后可以清楚地看到Python中的MRO(方法解析顺序)如何工作。
class A:
a = 8
class B:
b = 9
class C(A, B):
c = 99
输出
d = C() #After instantiating
print(d.a, d.b, d.c)
>> 8 9 99
# Without instantiating
print(C.a, C.b, C.c)
>> 8 9 99