子类不会默认调用父类的构造函数,但如果子类没有自己的构造函数则会默认调用父类的
class P(object):
def __init__(self):
print 'P inited'
def __del__(self):
print 'P deleted'
def fun(self):
print 'P fun'
class C(P):
def __init__(self):
print 'C inited'
def __del__(self):
print 'C deleted'
def fun(self):
super(C,self).fun()
print 'C fun'
class C2(P):
pass
>>> c = C()
C inited
>>> c.fun()
P fun
C fun
>>> delete c
SyntaxError: invalid syntax
>>> del c
C deleted
>>> c2 = C2()
P inited
多重继承,先继承的优先调用
class P1:
def __init__(self):
print 'P1 init()'
def foo(self):
print 'P1 foo()'
class P2:
def __init__(self):
print 'P2 init()'
def foo(self):
print 'P2 foo()'
def bar(self):
print 'P2 bar()'
class C1(P1,P2):
pass
class C2(P2,P1):
def bar(self):
print 'C2 bar()'
class GC(C1,C2):
pass
>>> c1 = C1()
P1 init()
>>> c2 = C2()
P2 init()
>>> c1.foo()
P1 foo()
>>> c1.bar()
P2 bar()
>>> c2.foo()
P2 foo()//先继承了P2,所以优先调用P2的foo
>>> c2.bar()
C2 bar()
>>> gc = GC()
P1 init()
>>> gc.foo
<bound method GC.foo of <__main__.GC instance at 0x0000000002F55588>>
>>> gc.foo()
P1 foo()//先继承了C1,C1再向上找到P1的foo
>>> gc.bar()
P2 bar()
>>>