【发布时间】:2016-05-02 02:55:32
【问题描述】:
最终类用户可能想要创建一个由Base 和Mixin 组成的类(Mixin 提供了超过 3rd 方库类的额外通用功能)。
但Mixin.__init__ 在如下使用时不会被调用。只调用了Base.__init__:
>>> class Base(object): #3rd party library class
... def __init__(self): print "Base"
...
>>> class Mixin(object): #my features useful as addendum for a few classes
... def __init__(self): print "Mixin"
...
>>> class C(Base, Mixin): pass
...
>>> c = C()
Base
如何在这种情况下强制同时调用Mixin.__init__ 和Base.__init__,而不需要用户记住将带有super() 调用的构造函数放在C 类中?
>>> class Base(object):
... def __init__(self): print "Base"
...
>>> class Mixin(object):
... def __init__(self): print "Mixin"
...
>>> class C(Base, Mixin):
... #easy to forget to add constructor
... def __init__(self): super(C, self).__init__()
...
>>> c = C()
Base
Mixin
【问题讨论】:
-
C.__init__不会同时打印;它调用Base.__init__,它不调用任何进一步的函数。
标签: python multiple-inheritance mixins super