標籤:廣度 需要 寫法 with lex 執行 def 深度優先 color
1 # class People: #經典類 2 class People(object): #新式類 3 def __init__(self,name,age): 4 self.name=name 5 self.age=age 6 self.friends=[] 7 def eat(self): 8 print("%s is eating." % self.name) 9 def sleep(self):10 print("%s is sleeping." % self.name)11 class Relation(object):12 def make_friends(self,obj):13 print(‘%s is making friends with %s‘ %(self.name,obj.name))14 self.friends.append(obj)15 obj.friends.append(self)16 17 class Man(People,Relation): #多繼承,繼承順序從左至右18 def __init__(self,name,age,money):19 # People.__init__(self,name,age)20 super(Man, self).__init__(name,age) #新式類寫法21 self.property=money22 print(‘%s has %s yuan when he was born‘%(self.name,self.property))23 def sleep(self): #重構24 #People.sleep(self) #繼承父類25 super(Man,self).sleep()26 print(‘%s is dahaning‘ % self.name)27 class Woman(Relation,People):
28 #多繼承(建構函式只需要一個),繼承順序從左至右,\
29 #第一個父類有建構函式,就不會執行第二個父類的建構函式;如果第一個父類沒有建構函式,就去第二個父類中找
30 pass
1 m1=Man(‘alex‘,33,10)2 w1=Woman(‘May‘,35)3 4 m1.make_friends(w1)5 print(m1.friends[0].name)6 print(w1.friends[0].name)
Man和Woman類都繼承了People和Relation兩個父類,但Relation類中沒有建構函式。Woman執行個體化時,會先去Relation類中去找建構函式,因為沒找到,所以去People類中再找建構函式(從左往右的順序)。
關於繼承順序:
在python2中新式類是按廣度優先繼承的,經典類是按深度優先繼承的
在python3中新式類和經典類都是按廣度優先繼承的
python多繼承