python 子类继承父类的__init__方法

父类A

class A(object):
    def __init__(self, name):
        self.name=name
print "name:", self.name
def getName(self): return 'A ' + self.name

子类不重写__init__,实例化子类时,会自动调用父类定义的__init__

class B(A):
    def getName(self):
        return 'B '+self.name
 
if __name__=='__main__':
    b=B('hello')
    print b.getName()

执行

$python lei2.py 
name: hello
B hello

但重写了__init__时,实例化子类,就不会调用父类已经定义的__init__

class A(object):
    def __init__(self, name):
        self.name=name
        print "name:", self.name
    def getName(self):
        return 'A ' + self.name

class B(A):
    def __init__(self, name):
        print "hi"
        self.name =  name
    def getName(self):
        return 'B '+self.name

if __name__=='__main__':
    b=B('hello')
    print b.getName()

执行

$python lei2.py 
hi
B hello

为了能使用或扩展父类的行为,最好显示调用父类的__init__方法

class A(object):
    def __init__(self, name):
        self.name=name
        print "name:", self.name
    def getName(self):
        return 'A ' + self.name

class B(A):
    def __init__(self, name):
        super(B, self).__init__(name)
        print "hi"
        self.name =  name
    def getName(self):
        return 'B '+self.name

if __name__=='__main__':
    b=B('hello')
    print b.getName()

执行

$python lei2.py
name: hello
hi
B hello

 

posted @ 2016-07-22 00:29  jihite  阅读(44266)  评论(0编辑  收藏  举报