父类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
本文转自jihite博客园博客,原文链接:http://www.cnblogs.com/kaituorensheng/p/5693677.html,如需转载请自行联系原作者