ikostia
ikostia

Reputation: 7587

How can I call a particular base class method in Python?

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?

Upvotes: 4

Views: 202

Answers (1)

unutbu
unutbu

Reputation: 879511

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)

Upvotes: 4

Related Questions