显示代码:
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
有两个基类——state
和event
,初始化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__()
我正在添加一些参考:
- From Raymond Hettinger
- StackOverflow
正如MisterMiyagi所说,super(state,self).init不表示">init在超类state"中,它表示">init在self的mro after状态下的超类"
我们可以用下面的方法删除state
和event
类中的所有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'