python 3.x 學習筆記10 (解構函式and繼承)

來源:互聯網
上載者:User

標籤:學習   使用   直接   資料庫   span   繼承   post   pytho   開啟   

1.類變數的用途:
大家公用的屬性,節省開銷(記憶體)

2.解構函式
在執行個體釋放和銷毀的時候執行的,通常用於做一些收尾工作,如關閉一些資料庫連結和開啟的臨時檔案

3.私人方法
兩個底線開頭,聲明該方法為私人方法,不能在類地外部調用。

4.私人屬性
兩個底線開頭,聲明該屬性為私人,不能在類地外部被使用或直接存取。

5.

繼承的時候重寫建構函式要先將父類的所有參數寫一遍加上子類變數,然後調用父類,再添加子類的執行個體化變數。

6.
python2.x 經典類是按深度有先來繼承的,新式類是按廣度有先來繼承的。

python3.x 經典類和新式類都是統一按廣度優先來繼承的。

 

練習

 1 #父類1 2 class Person(object):         #新式寫法 3  4     def __init__(self,name,age): 5         #建構函式 6         self.name = name           #執行個體化變數(靜態屬性) ,範圍為執行個體化本身 7         self.age = age 8         self.friends = [] 9 10     def eat(self):                  # 類方法 功能(動態屬性)11         print(‘%s will eat something ! ‘%self.name)12 13     def run(self):14         print(‘%s will runing !‘%self.name)15 16     def sleep(self):17         print(‘%s will sleep !‘%self.name)18 19 #父類220 class Relation(object):21     def make_friends(self,obj):22         print(‘%s make friend with %s‘% (self.name,obj.name))23         self.friends.append(obj)       #這裡傳的參數是obj,在這例題裡 obj既是 w124 25 26 #子類27 class Man(Person,Relation):                      #多繼承28     def __init__(self,name,age,money):           #重寫建構函式29         #Person.__init__(self,name,age,money)     #經典寫法30         super(Man,self).__init__(name,age)        #新式寫法,建議用這種寫法31         self.money = money32 33     def piao(self):34         print(‘%s is piaoing .......‘% self.name)35 36 37 #子類38 class Woman(Person,Relation):                 #多繼承39     def piao(self):40         print(‘%s is piaoing .......‘% self.name)41 42 m1 = Man(‘張三‘,20,10)43 44 w1 = Woman(‘lili‘,21)45 46 m1.make_friends(w1)47 print(m1.friends[0].name)48 print(m1.friends[0].age)49 50 # m1.piao()51 # m1.eat()52 # m1.run()53 # m1.sleep()

 

python 3.x 學習筆記10 (解構函式and繼承)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.