python - 学习继承时的意外结果
问题描述
我正在学习继承并遇到了这个问题
class A:
def test(self):
print("test of A called")
class B(A):
def test(self):
print("test of B called")
super().test()
class C(A):
def test(self):
print("test of C called")
super().test()
class D(B,C):
def test2(self):
print("test of D called")
obj=D()
obj.test()
根据发布此问题的网站,输出如下
test of B called
test of C called
test of A called
但在我看来,输出应该是
test of B called
test of A called
因为,B 类将首先被调用(Acc to MRO),然后super().test()
从 B 类调用,它将打印
test of A called
.
我在这里错在哪里?
解决方案
简短回答:B.test
调用时super().test()
,它使用原始对象的 MRO。它不只是查看B
的层次结构。
推荐阅读
- r - 滚动均方根而不是r中的均值
- php - 按类别进行两次查询
- android - Android UI 测试 Fragment 包含自定义视图
- regex - 正则表达式用 abcDef 整个单词替换 abc_def 避免 R.id.abc_def
- python - 由于缺少文件,“conda update --all”失败
- powershell - Powershell 复制匹配项
- vue.js - Antdv 表 - 选择复选框的自定义渲染
- r - 使用三个变量将 Str 替换为 Bash 代码块:搜索、替换和主题
- php - PHP XMLReader 不会对无效字符给出任何错误
- jquery - 无法向spring mvc控制器发送ajax post请求