繼承順序:python
class (A,B,C):按左右順序繼承app
1 class A(): 2 pass 3 class B(A): 4 pass 5 class C(A): 6 pass 7 class D(B,C): 8 pass
廣度優先:函數
在這種狀況下,先執行D中的構造函數;若D中沒有構造函數則在B中找,B中有則執行;若B沒有則在C中找,若C中也沒有則在A中找。在python3中,經典類和新式類都使用廣度優先執行。廣度優先效率比較高。spa
深度優先:code
在這種狀況下,先執行D中的構造函數;若D中沒有構造函數則在B中找,B中有則執行;若B沒有則在A中找,若A中也沒有則在C中找。在python2中,經典類按深度優先執行;新式類是按廣度優先來繼承的,blog
經典類寫法:class A:繼承
新式類寫法:class A(object):ip
1 #!/usr/bin/env python 2 # -*- coding:utf-8 -*- 3 # Author:James Tao 4 5 class People(object): #父類,實際上這也是繼承 6 7 def __init__(self,name,age): 8 self.name=name 9 self.age=age 10 self.friends=[] 11 12 def eat(self): 13 print('%s is eating...' % self.name) 14 15 def talk(self): 16 print('%s is talking...' % self.name) 17 18 def sleep(self): 19 print('%s is sleeping...' % self.name) 20 21 class Relationship(object): 22 23 def make_friends(self,obj): 24 print('%s is making friends with %s' % (self.name,obj.name)) 25 self.friends.append(obj) 26 27 class Man(People,Relationship): #子類,繼承Pelple,繼承多個父類:繼承順序從左到右,只執行People的init 28 #當類自己沒有構造函數時,從左到右找父類的構造函數init,執行第一個有構造函數的父類的構造函數 29 30 def __init__(self,name,age,money):#就不會調用父類的初始化了 31 #People.__init__(self,name,age) #父類的初始化要調用一遍,方法一 32 super(Man,self).__init__(name,age)#方法二,不用寫多個People 33 self.money=money 34 print('%s有%s元' % (self.name,self.money)) 35 36 def piao(self): #加新功能 37 print('%s is piaoing...' % self.name) 38 39 def sleep(self):#重構父類功能 40 People.sleep(self) 41 print('Man is sleeping...') 42 43 class Woman(People,Relationship): #子類,繼承People 44 45 def get_birth(self): 46 print('%s is delievered to a baby' % self.name) 47 48 man1=Man('James',23,10000) 49 man1.eat() 50 man1.sleep() 51 man1.piao() 52 53 woman1=Woman('Penny',23) 54 woman1.get_birth() 55 56 man1.make_friends(woman1) 57 print('%s的朋友名單有%s' % (man1.name,man1.friends[0].name))#
運行結果:utf-8