-1

I have the following situation in 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'?

It should also be noted that one of the parent classes, say A, is a library class and the solution should preferably assume it is set in stone; While the other class B is mine and could be freely changed.

What is the correct way to initialize both parent classes correctly? Thanks!

Idan
  • 5,365
  • 5
  • 24
  • 28

1 Answers1

0

Reverse the inheritance order and let your class to call super on the library one:

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'

The basic idea is to modify your superclass to take two arguments, one for itself and the other will be passed on to follow the MRO.

As an aside, you can drop the inheritance from object in Python 3.


Edit:

Python 2 requires super call with arguments:

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')
heemayl
  • 39,294
  • 7
  • 70
  • 76