Behaviour of Mutlple inheritance in python
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 | In [5]: class a(object): ...: def __init__(self): ...: print"In class a" ...: self.a = 1 ...: In [6]: class b(object): ...: def __init__(self): ...: print"In class b" ...: self.b = 2 ...: ...: In [7]: class c(b, a): ...: pass ...: In [8]: c.mro() Out[8]: [<class '__main__.c'>, <class '__main__.b'>, <class '__main__.a'>, <type 'object'>] In [9]: obj = c() In class b In [10]: obj.__dict__ Out[10]: {'b': 2} |
类
根据我的理解,如果我从2类继承,那么派生类对象应该具有来自这两个类的变量(除非它们对这些类是私有的)。
我的问题是:期望派生对象包含来自两个类的变量是错误的吗?如果是,为什么?难道不也叫
在Python中,默认情况下不调用来自上层类的初始化方法。要做到这一点,您必须使用super明确地调用它们,如下所示:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | class a(object): def __init__(self): super(a, self).__init__() print"In class a" self.a = 1 class b(object): def __init__(self): super(b, self).__init__() print"In class b" self.b = 2 class c(b, a): pass obj = c() |
示例输出。
In class a
In class b
编辑:关于为什么这样做,我想说这是基于python的zen的设计决策:
Explicit is better than implicit.