python多繼承

來源:互聯網
上載者:User

標籤:廣度   需要   寫法   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多繼承

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.