class ClsOne(object):
def __init__(self):
super(ClsOne, self).__init__()
print "Here's One"
class ClsTwo(ClsOne):
def __init__(self):
super(ClsTwo, self).__init__()
print "Here's Two"
class ClsThree(ClsTwo): # Refer to one blackbox object
def __init__(self):
# super(ClsThree, self).__init__()
print "Here's Three"
class ClsThreee(ClsTwo): # Refer to your custom object
def __init__(self):
super(ClsThreee, self).__init__()
print "Here's Threee"
class ClsFour(ClsThree, ClsThreee): # Multiple Inheritance
def __init__(self):
super(ClsFour, self).__init__()
print "Here's Four"
entity = ClsFour()
在这种情况下,您尝试将ClsThree(来自单个编译库并且很难更改)和您自己的ClsThree对象组合在一起。因为ClsThree忘记在其构造函数中调用super() ,所以他们的孩子在使用super()时无法执行 ClsThree 的构造函数。
结果,输出将如下所示:
Here's Three
Here's Four
显然,我可以手动调用 ClsFour 的每个基,而不是使用 super(),但是当这个问题分散在我的代码库中时,它有点复杂。
顺便说一句,那个黑盒的东西是 PySide :)
补充:
感谢@WillemVanOnsem 和@RaymondHettinger,解决了之前的ClsFour 问题。但是通过一些进一步的调查,我发现 PySide 中的类似问题没有相同的概念。
在 ClsFour 上下文中,如果您尝试运行:
print super(ClsFour, self).__init__
你会得到:
<bound method ClsFour.__init__ of <__main__.ClsFour object at 0x00000000031EC160>>
但在以下 PySide 上下文中:
import sys
from PySide import QtGui
class MyObject(object):
def __init__(self):
super(MyObject, self).__init__()
print "Here's MyObject"
class MyWidget(QtGui.QWidget, MyObject):
def __init__(self):
super(MyWidget, self).__init__()
app = QtGui.QApplication(sys.argv)
widget = MyWidget()
print super(MyWidget, widget).__init__
结果是:
<method-wrapper '__init__' of MyWidget object at 0x0000000005191D88>
它不打印“Here's MyObject”,并且 super() 的 init 属性也有不同的类型。以前,我尝试将这个问题简化为 ClsFour。但现在我认为它并不完全一样。
我猜这个问题出现在 shiboken 库中,但我不确定。
尖端:
这个问题也出现在 PyQt 上下文中,但是可以让 MyObject 继承自 QObject 来解决。这个解决方案在 PySide 中没有用。