2

I have a class that inherits from two other classes whose __init__ take both a parameter like this:

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, a, b):
        super(C, self).__init__(a, b)

c = ClassC(1, 2)

This gives a TypeError: __init__() takes exactly 2 arguments (3 given).

When setting b in B to a fixed value and passing only 1 parameter to super then trying to access b in C gives an AttributeError: 'ClassC' object has no attribute 'b':

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

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

class C(A, B):
    def __init__(self, a, b):
        super(C, self).__init__(a)

        print self.a
        print self.b

c = ClassC(1, 2)

When calling the __init__ manually everything seems to be fine:

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, a, b):
        A.__init__(a)
        B.__init__(b)

        print self.a
        print self.b

c = ClassC(1, 2)

So how can I get this inheritance straight and how can I manage the parameters for __init__ of inherited classes when using super? Is it even possible? How does super know which parameters are to pass to which class?

a_guest
  • 34,165
  • 12
  • 64
  • 118
  • 1
    You need super calls in other classes as well: [Python's super() considered super!](https://rhettinger.wordpress.com/2011/05/26/super-considered-super/) – Ashwini Chaudhary Feb 27 '15 at 01:21
  • Related: [Is `__init__` a class method?](http://stackoverflow.com/q/28577378/846892) – Ashwini Chaudhary Feb 27 '15 at 01:23
  • possible duplicates http://stackoverflow.com/questions/3277367/how-does-pythons-super-work-with-multiple-inheritance and http://stackoverflow.com/questions/14206015/pythons-multiple-inheritance-picking-which-super-to-call – Nikos M. Feb 27 '15 at 01:26

0 Answers0