4

Let's say, I have the following two classes:

class A(object):
    def __init__(self, i):
        self.i = i
class B(object):
    def __init__(self, j):
        self.j = j

class C(A, B):
    def __init__(self):
        super(C, self).__init__(self, 4)
c = C()

c will only have the i attribute set, not the j. What should I write to set both of attributes/only the j attribute?

1
  • Im guessing B would have to inherit from A and call super aswell Commented Sep 6, 2010 at 13:43

1 Answer 1

4

If you want to set only the j attribute, then only call B.__init__:

class C(A, B):
    def __init__(self):
        B.__init__(self,4)

If you want to manually call both A and B's __init__ methods, then of course you could do this:

class C(A, B):
    def __init__(self):
        A.__init__(self,4)
        B.__init__(self,4)

Using super is a bit tricky (in particular, see the section entitled "Argument passing, argh!"). If you still want to use super, here is one way you could do it:

class D(object):
    def __init__(self, i):
        pass
class A(D):
    def __init__(self, i):
        super(A,self).__init__(i)
        self.i = i
class B(D):
    def __init__(self, j):
        super(B,self).__init__(j)        
        self.j = j

class C(A, B):
    def __init__(self):
        super(C, self).__init__(4)
c = C()
print(c.i,c.j)
# (4, 4)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.