继承是面向对象的重要特征之一;
继承关系:继承是相对两个类而言父子关系,子类继承了父类的所有共有属性和方法
继承实现了代码重用
例如:class Myclass (ParentClass)
如果弗雷定义了__init__方法,子类必须显示调用父类的__init__方法:
ParentClass.__init__(self,[args..])
如果子类需要扩展父类的行为,可以添加__init__方法的参数
第一种:常规继承父类,通过类名.__init__()
People.__init__(self,'red')
class People(object): color='yellow' def think(self): print "i am a %s"% self.color print "i am a thinker" class Chinese(People): pass cn=Chinese() print cn.color cn.think()
class People(object): color='yellow' def __init__(self): print "__init..." self.dwell='earth' def think(self): print "i am a %s"% self.color print "i am a thinker" class Chinese(People): pass cn=Chinese() print cn.dwell cn.think()
class Chinese(People): def __init__(self): People.__init__(self,'red')super 函数也可以继承父类,在子类中定义super 函数
super(Chinese,self).__init__('red')
class A(object):
def __init__(self):
print "enter a"
print "leave a"
class B(A):
def__init__(self):
print "enter B"
super(B,self).__init__()
print“leave B”
b=B()
class Chinese(People): def __init__(self): # People.__init__(self,'red') super(Chinese,self).__init__('red')
多重继承
Python 支持多重继承,即一个类可以继承多个父类:
语法:
class class_name (Parent_c1,parent_c2)
当父类中出现多个自定义的__init__方法时,多重继承只执行第一个类的__init__方法,其他不执行。
class People(object): color='yellow' def __init__(self,): self.dwell='earth' def think(self): print "i am a %s"% self.color print "my home is %s"% self.dwell class Martian(object): color='red' def __init__(self): self.dwell='martian' class Chinese(People,Martian): def __init__(self): People.__init__(self) # super(Chinese,self).__init__()
class People(object): color='yellow' def __init__(self,): self.dwell='earth' self.color='yellow' def think(self): print "i am a %s"% self.color print "my home is %s"% self.dwell class Martian(object): color='red' def __init__(self): self.dwell='martian' def talk(self): print "i like talking" class Chinese(Martian,People): def __init__(self): People.__init__(self) cn=Chinese() cn.think() cn.talk()