python物件導向的繼承,python物件導向
沒什麼可說的,繼承主要就是繼承父類的一些方法,代碼中很詳細
#!/usr/bin/env python #coding:utf-8class Father(object):#新式類 def __init__(self): self.name='Liu' self.FamilyName='Yan' def Lee(self): print '我是父類函數Lee' def Allen(self): print "我是父類函數Allen" class Son(Father): def __init__(self): #Father.__init__(self) #經典類執行父類建構函式 super(Son,self).__init__() #新式類執行父類建構函式 self.name='Feng' def Aswill(self): #子類新增函數 print 'Son.Bar' def Lee(self):#重寫父類函數Lee print '子類重寫了父類函數Lee' s1=Son()print "繼承了父類的姓"+ s1.FamilyNameprint "重寫了父類的名字",s1.names1.Lee() #子類重寫了父類函數Lees1.Allen() #子類繼承了父類函數Allen
繼承多個類時的順序,經典類繼承是深度優先,是一個BUG, 新式類是廣度優先,應該是用新式類去定義類
新式類
class A(object): #新式類的寫法 def __init__(self): print 'This is from A' def test(self): print 'This is test from A'class B(A): def __init__(self): print "This is from B" class C(A): def __init__(self): print "This is from C" def test(self): print "This is test from C" class D(B,C): def __init__(self): print 'this is D' T1=D()T1.test()
經典類
class A(): def __init__(self): print 'This is from A' def test(self): print 'This is test from A'class B(A): def __init__(self): print "This is from B" class C(A): def __init__(self): print "This is from C" def test(self): print "This is test from C" class D(B,C): def __init__(self): print 'this is D' T1=D()T1.test()