Python 類的用法

來源:互聯網
上載者:User

標籤:方法調用   elf   __init__   資訊   ret   上海   inf   基本   end   

 1 #建立一個類的過程: 2 #建立一個對象01 3 #自動調用__init__方法,擷取基本屬性02 4 #返回建立對象的引用給當前執行個體03 5  6  7 class Home: 8     # 初始化定義屬性 9     def __init__(self, new_area, new_info, new_addr):10         self.area = new_area11         self.info = new_info12         self.addr = new_addr13         self.left_area = new_area14         self.contain_items = []15 16     # 該類的描述資訊17     def __str__(self):18         msg = "房子的總面積是:%d, 房屋的可用面積是:%d, 戶型是:%s, 地址是:%s"%(self.area, self.left_area, self.info, self.addr)19         msg += " 當前房子裡的物品有%s"%(str(self.contain_items))20         21         return msg22 23     def add_item(self,item):24         # self.left_area -= item.area         # 屬性調用法25         # self.contain_items.append(item.name)26 27         self.left_area = item.get_area()        # 方法調用法28         self.contain_items.append(item.get_name())29 30 31 class Bed:32     def __init__(self, new_name, new_area):33         self.name = new_name34         self.area = new_area35 36     def __str__(self):37         return "床的品牌是:%s,面積是:%d"%(self.name,self.area)38 39     def get_area(self):40         return self.area41 42     def get_name(self):43         return self.name44     45 46 # 執行個體化47 fangzi = Home(130, "三室一廳", "上海市 浦東新區 唐鎮 唐人苑")48 # 類資訊列印49 print(fangzi)50 51 52 bed1 = Bed("席夢思", 4)53 print(bed1)54 55 # 方法調用56 fangzi.add_item(bed1)57 print(fangzi)58 59 60 bed2 = Bed("三人床", 6)61 fangzi.add_item(bed2)62 print(fangzi)

 

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.