日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > python >内容正文

python

python多继承

發布時間:2025/7/14 python 36 豆豆
生活随笔 收集整理的這篇文章主要介紹了 python多继承 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
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=money 22 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中新式類和經典類都是按廣度優先繼承的
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() 廣度優先:

B->C->A

?

轉載于:https://www.cnblogs.com/ceceliahappycoding/p/8410724.html

總結

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

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。