|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
小甲鱼老师在讲解钻石继承时举以下两个例子.
[例题2]
第一个例子没有使用super()构造函数,会导致钻石继承问题,例题如下:
>>> class A:
... def __init__(self):
... print("哈喽,我是A~")
...
>>> class B1(A):
... def __init__(self):
... A.__init__(self)
... print("哈喽,我是B1~")
...
>>> class B2(A):
... def __init__(self):
... A.__init__(self)
... print("哈喽,我是B2~")
...
>>> class C(B1, B2):
... def __init__(self):
... B1.__init__(self)
... B2.__init__(self)
... print("哈喽,我是C~")
>>> c = C()
执行结果如下:
哈喽,我是A~
哈喽,我是B1~
哈喽,我是A~
哈喽,我是B2~
哈喽,我是C~
这里” 哈喽,我是B1~”是在” 哈喽,我是B2~”的上面.
[例题2]
第二个例子使用super()构造函数,解决钻石继承问题,例题如下:
>>> class B1(A):
... def __init__(self):
... super().__init__()
... print("哈喽,我是B1~")
...
>>> class B2(A):
... def __init__(self):
... super().__init__()
... print("哈喽,我是B2~")
...
>>> class C(B1, B2):
... def __init__(self):
... super().__init__()
... print("哈喽,我是C~")
...
>>> c = C()
执行结果如下:
哈喽,我是A~
哈喽,我是B2~
哈喽,我是B1~
哈喽,我是C~
[问题]
我的困惑是在使用super()语句解决钻石问题后,为何执行结果却是将” 哈喽,我是B2~”变成在” 哈喽,我是B1~”的上面?虽然这里类C的MRO顺序都一样([__main__.C, __main__.B1, __main__.B2, __main__.A, object]).
”
|
|