python - 无法在 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 ......但这显然没有发生。
是什么赋予了?
解决方案
你正在做的是你试图访问类变量和(或)属性,而不实际告诉它属于哪个类或不引用该类。 您可以查看@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
推荐阅读
- json - Spring Boot JSON 过滤器
- lambda - 使用python 2.7使用lambda函数停止AWS极光数据库
- c# - Android Unity 中语音命令的调用函数
- json - 管理来自服务器的响应类型
- cucumber-jvm - 我可以在黄瓜 Java 中运行/使用 3 个带有单步定义文件的功能文件吗
- java - 需要复制构造函数说明
- apache-kafka - 一位消费者宕机/崩溃时的 Kafka 消费者行为
- facebook - 是否可以将一个聊天机器人中的 user_id 与其他聊天应用程序一起使用?
- c++ - 为什么即使在包含 math.h 并使用 -lm 链接到数学库之后我也会收到“未定义的符号:.sqrtf”
- php - 从数据库表php mysql中获取数据时如何忽略空值