一、 子类不重写__init__
, 实例化子类时,会自动调用父类定义的__init__
二、 子类
重写了__init__
时,实例化子类,就不会调用父类已经定义的__init__
三、
为了能使用或扩展父类的行为,要显示调用父类的__init__
方法,有以下两种调用方式。
1. 调用未绑定的父类构造方法
class FooParent(object): #父类
def __init__(self):
self.parent = 'I\'m the parent.'
print 'Parent'
def bar(self,message):
print message, 'from Parent'
class FooChild(FooParent): #子类
def __init__(self):
FooParent.__init__(self) #调用未绑定的超类构造方法【必须显式调用父类的构造方法,否则不会执行父类构造方法,这个跟Java不一样】
print 'Child'
def bar(self,message):
FooParent.bar(self,message)
print 'Child bar function.'
print self.parent
if __name__=='__main__':
fooChild = FooChild()
fooChild.bar('HelloWorld')
2. super继承:使用super需要继承object对象,属于新式类。super函数会返回一个super对象 ,这个对象负责进行方法解析,解析过程中会自动查找所有父类以及父类的父类。super函数比在超类中直接调用未绑定方法更加直观,但是最大的优点是如果子类继承了多个父类,它只需要使用一次super函数就可以。而如果没有这个需求,直接使用FooParent.__init__(self)更加直观.
class FooParent(object):
def __init__(self):
self.parent = 'I\'m the parent.'
print 'Parent'
def bar(self,message):
print message,'from Parent'
class FooChild(FooParent):
def __init__(self):
super(FooChild,self).__init__() #使用super函数
print 'Child'
def bar(self,message):
super(FooChild, self).bar(message) #super 调用实例方法
print 'Child bar fuction'
print self.parent
if __name__ == '__main__':
fooChild = FooChild()
fooChild.bar('HelloWorld')