python物件導向-4類的繼承與方法的重載,python-4

來源:互聯網
上載者:User

python物件導向-4類的繼承與方法的重載,python-4

 1.類的繼承與方法的重載

 

上面就是先定義了一個類A,然後由定義了一個類B,B繼承了類A,這樣B就有了A的非私人屬性和方法。

 1 class Washer: 2     company='ZBL' 3     def __init__(self,water=10,scour=2): 4         self._water=water #不想讓使用者直接存取執行個體變數,可以標誌成私人 5         self.scour=scour 6         self.year=2000#這是生產日期 7         #屬性包裝,將water屬性包裝成方法,使用者使用water時實際是訪問的方法 8     @staticmethod #定義一個靜態方法 9     def spins_ml(spins):10         return spins*0.411         print('company:',Washer.company)12         #print('year:',self.year)#錯誤,靜態方法不能使用執行個體屬性13     @classmethod14     def get_washer(cls,water,scour):#cls相當於執行個體方法中的self,調用是不用提供這個參數15         return cls(water,cls.spins_ml(scour))#cls代表類名Washer,故不是寫入程式碼(改類名是不用改cls,若cls用類名代替也對,但若改類名這個地方也需要改動)16     17     @property18     def water1(self):#如果使用者使用 執行個體.water相當於訪問這個方法,而不是真的訪問屬性19         return self._water20     21     @water1.setter22     def water1(self,water):23         if 0<water<=500:24             self._water=water25         else:26             print('set Failure!')27     @property28     def total_year(self):29         return 2017-self.year30     31     def set_water(self,water):32         self.water=water        33 34     def set_scour(self,scour):35         self.scour=scour        36 37     def add_water(self):38         print('Add water:',self._water)39 40     def add_scour(self):41         print('Add scour:',self.scour)42 43     def start_wash(self):44         self.add_water()45         self.add_scour()46         print('Start wash...')47         48 class WasherDry(Washer):# 建立一個新類,繼承自Washer49     def dry(self):#新類中可以定義只屬於子類的新方法50         print('Dry cloths...')51     def start_wash(self):#在子類中新定義與父類同名的方法就是方法的重載52         self.add_scour()53         self.add_water()54         55 if __name__=='__main__':56 ##    print(Washer.spins_ml (8))57 ##    w=Washer()58 ##    print(w.spins_ml(8))59 ##    w=Washer(200,Washer.spins_ml(8))60 ##    w.start_wash()61     w=WasherDry()62     w.start_wash()63     print(w.scour,w.company)64     w.dry()

 

聯繫我們

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