如何在Python中调用特定的基类方法?

iko*_*tia 4 python

比方说,我有以下两个类:

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()
Run Code Online (Sandbox Code Playgroud)

c只会设置i属性,而不是j.我应该写什么来设置两个属性/只有j属性?

unu*_*tbu 5

如果只想设置j属性,则只调用B.__init__:

class C(A, B):
    def __init__(self):
        B.__init__(self,4)
Run Code Online (Sandbox Code Playgroud)

如果你想手动调用这两个AB__init__方法,那么你当然可以这样做:

class C(A, B):
    def __init__(self):
        A.__init__(self,4)
        B.__init__(self,4)
Run Code Online (Sandbox Code Playgroud)

使用super有点棘手(尤其是看到标题为"参数传递,哎呀!").如果您仍想使用super,可以采用以下方法:

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)
Run Code Online (Sandbox Code Playgroud)