日韩av黄I国产麻豆传媒I国产91av视频在线观看I日韩一区二区三区在线看I美女国产在线I麻豆视频国产在线观看I成人黄色短片

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁 >

python多继承

發(fā)布時間:2025/7/14 51 豆豆
生活随笔 收集整理的這篇文章主要介紹了 python多继承 小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
1 # class People: #經(jīng)典類 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=money 22 print('%s has %s yuan when he was born'%(self.name,self.property)) 23 def sleep(self): #重構(gòu) 24 #People.sleep(self) #繼承父類 25 super(Man,self).sleep() 26 print('%s is dahaning' % self.name) 27 class Woman(Relation,People):

28 #多繼承(構(gòu)造函數(shù)只需要一個),繼承順序從左到右,\
29 #第一個父類有構(gòu)造函數(shù),就不會執(zhí)行第二個父類的構(gòu)造函數(shù);如果第一個父類沒有構(gòu)造函數(shù),就去第二個父類中找

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類中沒有構(gòu)造函數(shù)。Woman實例化時,會先去Relation類中去找構(gòu)造函數(shù),因為沒找到,所以去People類中再找構(gòu)造函數(shù)(從左往右的順序)。

關(guān)于繼承順序:

在python2中新式類是按廣度優(yōu)先繼承的,經(jīng)典類是按深度優(yōu)先繼承的
python3中新式類和經(jīng)典類都是按廣度優(yōu)先繼承的
1 class A(object): 2 def __init__(self): 3 print('A') 4 class B(A): 5 pass 6 # def __init__(self): 7 # print('B') 8 class C(A): 9 def __init__(self): 10 print('C') 11 class D(B,C): 12 pass 13 14 15 d=D() 廣度優(yōu)先:

B->C->A

?

轉(zhuǎn)載于:https://www.cnblogs.com/ceceliahappycoding/p/8410724.html

總結(jié)

以上是生活随笔為你收集整理的python多继承的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯,歡迎將生活随笔推薦給好友。