在Python 2.7.10中
class OneMixin(object):
def __init__(self):
# super(OneMixin, self).__init__()
print "one mixin"
class TwoMixin(object):
def __init__(self):
# super(TwoMixin, self).__init__()
print "two mixin"
class Account(OneMixin, TwoMixin):
def __init__(self):
super(Account, self).__init__()
print "account"
Account.mro()是:[<class 'Account'>, <class 'OneMixin'>, <class 'TwoMixin'>, <type 'object'>]
虽然MRO中列出了每一个类,但并没有打印“two mixin”
如果我取消对OneMixin和TwoMixin中的超级调用的注释,那么MRO是完全相同的,但是会打印“TwoMixin”
为什么不同?我希望MRO里的每一件事都能被叫来
这是因为
super
用于将调用委托给类型的父类或同级类Python documentation对第二个用例有如下描述:如果从
OneMixin
中删除super
调用,那么在MRO中没有任何东西可以将调用委托给下一个类型原因是您正在重写父类的
__init__
方法。不管__init__
方法中有什么,方法的解析顺序都是相同的super
的工作方式是,它将按方法解析顺序将其传递给下一个类。通过注释掉OneMixin
中的那一行,你就打破了链条super
是为合作继承而设计的而且,
__init__
也不是真正的类构造函数。如果你把它看作是其他语言中的构造器的话,这可能会把你绊倒相关问题 更多 >
编程相关推荐