多重继承,给父母双方的构造函数一个参数

时间:2018-08-19 18:57:25

标签: python python-2.7 multiple-inheritance

在python 2.7中,我遇到以下情况

class A(object):
     def __init__(self, a):
           self._a = a

class B(object):
     def __init__(self, b):
           self._b = b

class C(A, B):
     def __init__(self):
           # How to init A with 'foo' and B with 'bar'?

还应注意,父类之一(例如A)是库类,解决方案最好假定它是固定的。而其他B类是我的,可以自由更改。

正确初始化两个父类的正确方法是什么? 谢谢!

1 个答案:

答案 0 :(得分:0)

颠倒继承顺序,让您的类在库1上调用super

In [1375]: class A(object):
      ...:      def __init__(self, a):
      ...:            self._a = a
      ...: 
      ...: class B(object):
      ...:      def __init__(self, b, a):
      ...:            self._b = b
      ...:            super().__init__(a)
      ...: 
      ...: class C(B, A):
      ...:      def __init__(self):
      ...:          super().__init__('bar', 'foo')
      ...:          

In [1376]: c = C()

In [1377]: c._a
Out[1377]: 'foo'

In [1378]: c._b
Out[1378]: 'bar'

基本思想是修改您的超类以接受两个参数,一个用于自身,另一个将传递给MRO。

顺便说一句,您可以在Python 3中放弃对object的继承。


编辑:

Python 2需要使用参数进行super调用:

class B(object):
    def __init__(self, b, a):
        self._b = b
        super(B, self).__init__(a)

class C(B, A):
    def __init__(self):
        super(C, self).__init__('bar', 'foo')
相关问题