Let's say, I have the following two classes:
class A(obj开发者_运维问答ect):
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)
精彩评论