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)
2
  • 3
    See also: super() considered super. Contrary to what the accepted answer of stackoverflow.com/q/4029550/395760 claims, it is very much possible. Commented Aug 27, 2013 at 6:11
  • Good read! Thanks, delnan. Commented Aug 27, 2013 at 6:26

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks :) Worked like a charm!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.