【发布时间】:2021-11-23 06:43:18
【问题描述】:
在帖子中,super() 被描述为:describe super()
super() looks at the next class in the MRO (method resolution order, accessed with cls.__mro__) to call the methods.
有些材料甚至给出了更明确的定义: more clear definition on super()
def super ( cls , inst ) :
mro = inst.__class__.mro( )
return mro[mro.index( cls ) + 1 ]
创建一个多重继承类结构如下:
class state():
def __init__(self):
pass
class event():
def __init__(self):
pass
class happystate(state,event):
def __init__(self):
print(super())
print(super(happystate,self))
mro 列表:
>>> happystate.__mro__
(<class '__main__.happystate'>, <class '__main__.state'>, <class '__main__.event'>, <class 'object'>)
happystate 类中的super() 将查看 MRO 中的下一个类,在此状态下是 state 类。
x=happystate()
<super: <class 'happystate'>, <happystate object>>
<super: <class 'happystate'>, <happystate object>>
为什么happystate类中的super()指向自身而不是MRO列表中的下一个类----state?
如果super() 指向state,则输出应为:
x=happystate()
<super: <class 'state'>, <state object>>
<super: <class 'state'>, <state object>>
【问题讨论】:
-
它不指向自己,
super()返回一个super object。注意前面的<super:。
标签: python-3.x multiple-inheritance super