【发布时间】:2018-10-07 02:21:36
【问题描述】:
文档是这样说的:
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 类......但这显然不会发生。
什么给了?
【问题讨论】:
-
这与多重继承无关,您正在尝试访问未定义的变量。
c1_1。你的意思是self. c1_1 -
如果您访问属性,Python 只会进行基于类的查找。在
dump中你永远不会尝试这样做
标签: python python-3.x inheritance multiple-inheritance