1. 子类不定义构造函数时候,默认引用父类构造函数
class A(object): def __init__(self,name): self.name = name def run(self): print 'name is',self.name class B(A): def run(self): print 'B name is',self.name b = B('pp') #此处实例化时候需要定义父类的参数 b.run()
Result:
B name is pp
[Finished in 0.1s]
2. 子类定义了构造函数,默认不会引用父类构造函数
class A(object): def __init__(self,name): self.name = name def run(self): print 'name is',self.name class B(A): def __init__(self,passwd): #此处定义自身参数 self.passwd=passwd #初始化自身属性 def run(self): print 'passwd is',self.passwd b = B('pp') b.run()
Result:
passwd is pp
[Finished in 0.1s]
3. 子类定义了构造函数,如果需要使用父类构造函数需要显示调用
class A(object): def __init__(self,name): self.name = name def run(self): print 'name is',self.name class B(A): def __init__(self,name,passwd): #此处定义要包含基类参数 super(B,self).__init__(name) #引用基类参数 self.passwd=passwd #初始化自身属性 def run(self): print "name is",self.name,'passwd is',self.passwd b = B('tom','pp') b.run()
Result:
name is tom passwd is pp
[Finished in 0.1s]