简体   繁体   中英

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?

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)

Check this links Things to Know About Python Super

Above link explains lot about inheritance and usage of super.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM