首页 > 解决方案 > 无法在 Python3 中解决多重继承问题

问题描述

文档是这样说的:

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 ......但这显然没有发生。

是什么赋予了?

标签: pythonpython-3.xinheritancemultiple-inheritance

解决方案


你正在做的是你试图访问类变量和(或)属性,而不实际告诉它属于哪个类或不引用该类。 您可以查看@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

推荐阅读