2

What is the best way to deal with an inheritance structure like this:

class A(object):
    def __init__(self):
        print('A')

class B(A):
    def __init__(self, foo):
        super(B, self).__init__()
        self.foo = foo
        print('B')

class C(A):
    def __init__(self, bar):
        super(C, self).__init__()
        self.bar = bar
        print('C')

class D(B, C):
    def __init__(self, foo, bar):
        super(D, self).__init__(foo, bar)

Essentially, I want to be able to call:

>>> d = D('bar', 'ram ewe')
>>> d.foo
'bar'
>>> d.bar
'ram ewe'

Currently, the super(D, self).__init__(foo, bar) raises TypeError: __init__() takes exactly 2 arguments (3 given)

EDIT

Working answer, thanks to Daniel Roseman.

class A(object):
    def __init__(self, *args, **kwargs):
        print('A')

class B(A):
    def __init__(self, foo, *args, **kwargs):
        super(B, self).__init__(*args, **kwargs)
        self.foo = foo
        print('B')

class C(A):
    def __init__(self, bar, *args, **kwargs):
        super(C, self).__init__(*args, **kwargs)
        self.bar = bar
        print('C')

class D(B, C):
    def __init__(self, foo, bar, *args, **kwargs):
        super(D, self).__init__(foo, bar, *args, **kwargs)
Josha Inglis
  • 1,018
  • 11
  • 23
  • 3
    See also: [super() considered super](http://rhettinger.wordpress.com/2011/05/26/super-considered-super/). Contrary to what the accepted answer of http://stackoverflow.com/q/4029550/395760 claims, it is very much possible. –  Aug 27 '13 at 06:11
  • Good read! Thanks, delnan. – Josha Inglis Aug 27 '13 at 06:26

1 Answers1

3

The best way is to always ensure the methods are both defined and called using the *args, **kwargs syntax. That means they will get the parameters they need and ignore the rest.

Daniel Roseman
  • 588,541
  • 66
  • 880
  • 895