为什么当 super() 具有多重继承时不能调用所有__init__?



显示代码:

class state():
def __init__(self):
print('in the state class')
self.state = "main state"
class event():
def __init__(self):
print("in the event class")
self.event = "main event"
class happystate(state,event):
def __init__(self):
print('in the happy state class')
super(state,self).__init__()
super(event,self).__init__()

happystate有两个基类——stateevent,初始化happystate

a = happystate()
in the happy state class
in the event class

为什么不能调用状态类?

如果你不在其他类中使用super().__init__(),并且你有多重继承,python将停止运行其他__init__方法。

class state():
def __init__(self):
super().__init__()
print('in the state class')
self.state = "main state"
class event():
def __init__(self):
super().__init__()
print("in the event class")
self.event = "main event"
class happystate(state,event):
def __init__(self):
print('in the happy state class')
super().__init__()

我正在添加一些参考:

  1. From Raymond Hettinger
  2. StackOverflow

正如MisterMiyagi所说,super(state,self).init不表示">init在超类state"中,它表示">init在self的mro after状态下的超类"

我们可以用下面的方法删除stateevent类中的所有super().__init__():

class state():
def __init__(self):
print('in the state class')
self.state = "main state"
class event():
def __init__(self):
print("in the event class")
self.event = "main event"
class happystate(state,event):
def __init__(self):
print('in the happy state class')
super(happystate,self).__init__()
super(state,self).__init__()

初始化happystate:

>>> x = happystate()
in the happy state class
in the state class
in the event class
>>> x.state
'main state'
>>> x.event
'main event'

相关内容

  • 没有找到相关文章

最新更新