https://docs.python.org/2/tutorial/classes.html#multiple-inheritance
http://www.jackyshen.com/2015/08/19/multi-inheritance-with-super-in-Python/
http://python.jobbole.com/85685/
在多继承中,如何访问父类中某个属性,是按照__mro__中的顺序确定的。
关于super(),原型是这样的:
super
(type[, object-or-type])
note:If the second argument is omitted, the super object returned is unbound. If the second argument is an object, isinstance(obj, type)
must be true. If the second argument is a type, issubclass(type2, type)
must be true (this is useful for classmethods).
在初始化的时候,如果使用了super()(ref:https://docs.python.org/2/library/functions.html#super),
那么会按照__mro__中的顺序初始化遇到的第一个父类
如果想初始化所有父类,就要用显式的方法了,比如,定义类:
A, B, C(A, B)
那么在C中可以这样初始化父类A:
A.__init__(self)
假如没有调用A的构造函数,那么在A的构造函数中定义的变量就不能访问,尽管C是A的子类
因为并没有把A的构造函数中定义的变量绑定在C的实例上
但是A的方法还是可以调用,调用的顺序由__mro__决定:
class A(object): def __init__(self): self.a = 1 print ‘A‘ def sing(self): print ‘sing A‘ class B(object): def __init__(self): print ‘B‘ class C(A, B): def __init__(self): print ‘C‘ c = C() c.sing() # ok print c.a # error
MRO的全称是method resolution order, 它定义了一种在多重继承的情况下依次访问父类的顺序
文档里(https://docs.python.org/2/library/functions.html#super)这样描述MRO:
The __mro__
attribute of the type lists the method resolution search order used by both getattr()
and super()
. The attribute is dynamic and can change whenever the inheritance hierarchy is updated.
目前Python2.7中的新式类,Python3中的类获取MRO使用的是C3算法(ref:https://en.wikipedia.org/wiki/C3_linearization)
原文地址:https://www.cnblogs.com/geeklove01/p/9048180.html