python面向對象-1方法、構造函數

類是指:描述一種事物的定義,是個抽象的概念?
實例指:該種事物的一個具體的個體,是具體的東西?

打個比方:?
“人”是一個類。“張三”是人類的一個具體例子?

在編程時也是同樣的道理,你先自己定義一個“類”,當你需要用時,用“類”的定義來創造一個具體的例子。?

用類的定義來創建一個實例,就叫做類的實例化。
實例化過程就是調用類的構造函數,完成該實例的數據分配

下面用一個洗衣機的例子來演示:

這個是一個簡單的手動洗衣機 w 實例化了Washer類:

 1 #class Washer:
 2 class Washer:#定義一個Washer類
 3 
 4     def __init__(self): #這是定義類的構造函數,也是一個特殊的實例方法
 5         self.water=0   #實例的屬性(變量)
 6         self.scour=0
 7 
 8     def add_water(self,water):#實例的方法(函數),可以接受實例化后傳過來的參數給類內實例變量,又因為實例繼承了類的屬性和方法,所以
 9     #相當于傳遞給了類的實例化對象的實例變量
10         print('Add water:',water)
11         self.water=water#在類的方法內引用實例變量用 self.屬性名
12 
13     def add_scour(self,scour):
14         self.scour=scour
15         print('Add scour:',scour)
16 
17     def start_wash(self):
18         print('Start wash...')
19         
20 if __name__=='__main__':
21     w=Washer()#類的實例化
22     w.add_water(10)#傳遞參數到實例變量
23     w.add_scour(2)
24     w.start_wash()

執行結果:

?

類內定義實例方法需要手動加上self參數(如第4行),但在類實例化后調用這個方法時不必手動加self參數,python會自動添加,如第22行。

實例化方法是 w=Washer() ?,可以看出需要在類后加一個括號。

類外調用類內定義的實例方法可以 實例名.方法名() ,例如

w.add_scour(2),必要的時候加上參數。

?


?下面改動一下程序,弄成半自動洗衣機,即在類的內部,方法之間相互調用。

washa.py:

 1 class Washer:
 2 
 3     def __init__(self):
 4         self.water=0
 5         self.scour=0
 6 
 7     def set_water(self,water):
 8         self.water=water
 9         self.add_water()
10 
11     def set_scour(self,scour):
12         self.scour=scour
13         self.add_scour()#在類內調用函數,用 self.方法名
14 
15     def add_water(self):
16         print('Add water:',self.water)
17 
18     def add_scour(self):
19         print('Add scour:',self.scour)
20 
21     def start_wash(self):
22         print('Start wash...')
23         
24 if __name__=='__main__':
25     w=Washer()
26     w.set_water(10)
27     w.set_scour(2)
28     w.start_wash()
29     

也可以改成:

 1 class Washer:
 2 
 3     def __init__(self):
 4         self.water=0
 5         self.scour=0
 6 
 7     def set_water(self,water):
 8         self.water=water        
 9 
10     def set_scour(self,scour):
11         self.scour=scour        
12 
13     def add_water(self):
14         print('Add water:',self.water)
15 
16     def add_scour(self):
17         print('Add scour:',self.scour)
18 
19     def start_wash(self):
20         self.add_water()
21         self.add_scour()
22         print('Start wash...')
23         
24 if __name__=='__main__':
25     w=Washer()
26     w.set_water(10)
27     w.set_scour(2)
28     w.start_wash()

運行結果:


做如下改動,用戶可以不設置洗衣機加水和洗滌劑量也可以洗衣服:

?

 1 class Washer:
 2 
 3     def __init__(self):
 4         self.water=10#將實例屬性修改為默認的標準洗衣程序需要的量
 5         self.scour=2
 6 
 7     def set_water(self,water):
 8         self.water=water        
 9 
10     def set_scour(self,scour):
11         self.scour=scour        
12 
13     def add_water(self):
14         print('Add water:',self.water)
15 
16     def add_scour(self):
17         print('Add scour:',self.scour)
18 
19     def start_wash(self):
20         self.add_water()
21         self.add_scour()
22         print('Start wash...')
23         
24 if __name__=='__main__':
25     w=Washer()
26 ##    w.set_water(10) #這兩行代碼注釋掉,代表用戶不必設置水和洗滌劑量
27 ##    w.set_scour(2)
28     w.start_wash()
29     

但是這樣,只能加入10L水和2L洗滌劑,不好,要改進。用到構造函數。

?


?

 1 class Washer:
 2 
 3     def __init__(self,water=10,scour=2):
 4         self.water=water
 5         self.scour=scour
 6 
 7     def set_water(self,water):
 8         self.water=water        
 9 
10     def set_scour(self,scour):
11         self.scour=scour        
12 
13     def add_water(self):
14         print('Add water:',self.water)
15 
16     def add_scour(self):
17         print('Add scour:',self.scour)
18 
19     def start_wash(self):
20         self.add_water()
21         self.add_scour()
22         print('Start wash...')
23         
24 if __name__=='__main__':
25     w=Washer()
26     w.start_wash()
27 
28     wb=Washer(100,10)
29     wb.start_wash()
30 
31     wc=Washer(100,10)
32     wc.set_water(50)
33     wc.set_scour(5)
34     wc.start_wash()
35 
36     
37 
38     
39     

運行結果:?

構造函數可以使類在實例化時實例對象更加豐富,具有實例化不同種類的實例的作用。

?

轉載于:https://www.cnblogs.com/zhubinglong/p/6945717.html

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/395541.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/395541.shtml
英文地址,請注明出處:http://en.pswp.cn/news/395541.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

bzoj3503: [Cqoi2014]和諧矩陣

高斯消元解異或方程組。學了bitset。對比如下 #include<cstdio> #include<cstring> #include<iostream> #include<algorithm> using namespace std; #define REP(i,s,t) for(int is;i<t;i) #define dwn(i,s,t) for(int is;i>t;i--) #define clr(…

她偏愛雛菊一樣的淡黃色_為什么開源項目(非常)偏愛新用戶,以及您可以采取什么措施...

她偏愛雛菊一樣的淡黃色by Filip Hracek由Filip Hracek 為什么開源項目(非常)偏愛新用戶&#xff0c;以及您可以采取什么措施 (Why open source projects (sadly) favor new users, and what you can do about it) Every now and then, all developer products (SDKs, framewo…

linux 腳本 expected,Linux | shell與expect結合使用

在linux操作系統下&#xff0c;使用腳本自動化&#xff0c;一般由兩種方案。方案一&#xff1a;telnetftp方案二&#xff1a;sshscpexpect。以下主要使用sshscpexpect為例進行說明使用方式。第一步&#xff1a;安裝expect&#xff1a;yum -y install expect第二步&#xff1a;驗…

[Swift]LeetCode246.對稱數 $ Strobogrammatic Number

★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★?微信公眾號&#xff1a;山青詠芝&#xff08;shanqingyongzhi&#xff09;?博客園地址&#xff1a;山青詠芝&#xff08;https://www.cnblogs.com/strengthen/&#xff09;?GitHub地址&a…

C++中父類的虛函數必需要實現嗎?

一、情景 C中父類的虛函數必需要實現嗎&#xff1f; class Vir{ public:virtual void tryVirtual(); };class CVir:public Vir{ public:void tryVirtual(){std::cout<<"CVir"<<std::endl;} };二、說明 &#xff08;1&#xff09;在main函數中&#xff0c…

解決新浪微博API調用限制 突破rate_limit_status瓶頸

新浪微博開放平臺API的調用和TWITTER接口一樣&#xff0c;都是受限的&#xff0c;以小時為單位進行限定。 他有兩個限制原則 1.用戶不登錄基于IP的限制&#xff0c;每小時1000次 2.用戶登錄了基于用戶的限制&#xff0c;每小時1000次 如果應用是用戶不登錄的那么就是對IP進行限…

chrome前端開發工具_精通Chrome開發人員工具:更高級別的前端開發技術

chrome前端開發工具by Ben Edelstein通過本愛德斯坦 You may already be familiar with the basic features of the Chrome Developer Tools: the DOM inspector, styles panel, and JavaScript console. But there are a number of lesser-known features that can dramatica…

linux給文件夾圖標,linux – 如何在GNOME中以編程方式設置自定義文件夾圖標?

我終于想出了如何做到這一點&#xff01;這是一個在標準Gnome環境中工作的Python腳本&#xff1a;#!/usr/bin/env pythonimport sysfrom gi.repository import Gioif len(sys.argv) not in (2, 3):print Usage: {} FOLDER [ICON].format(sys.argv[0])print Leave out ICON to u…

jQuery序列化表單為JSON對象

[html] view plaincopy <form id"myform"> <table> <tr> <td>姓名:</td> <td> <input type"text" name"name" /> </td> </tr> …

sys模塊

與python解釋器交互的模塊 sys.argv 命令行參數List&#xff0c;第一個元素是程序本身路徑 sys.exit(n) 退出程序&#xff0c;正常退出時exit(0),錯誤退出sys.exit(1) sys.version 獲取Python解釋程序的版本信息 sys.path 返回模塊的搜索路徑…

李開復:年輕人該比誰更拼命嗎?

李開復:年輕人該比誰更拼命嗎&#xff1f; IT職場 cricode 4個月前 (04-02) 951℃ 0評論 我年輕的時候是最不注重睡眠的&#xff0c;我記得在我讀大學的時候每次要考試就因為平時玩耍太多了&#xff0c;每次要考試的時候就會灌咖啡&#xff0c;有時候一個晚上可以喝十杯咖啡不…

linux命令無視錯誤,llinux 的一些命令和錯誤

sudo tar -zxvf ./hadoop-2.6.0.tar.gz -C /usr/local # 解壓到/usr/local中source ~/.bashrc # 使變量設置生效sudo useradd -m hadoop -s /bin/bash 創建新用戶sudo adduser hadoop sudo 可為 hadoop 用戶增加管理員權限sudo mv ./hadoop-2.6.0/ ./hadoop # 將文件…

假設檢驗方差未知_設計云數據庫時如何處理未知數并做出假設

假設檢驗方差未知by Rick Mak麥瑞克(Rick Mak) 設計云數據庫時如何處理未知數并做出假設 (How to handle unknowns and make assumptions when designing a cloud database) 場景&#xff1a;鞋盒還是社交應用&#xff1f; (Scenario: Shoebox or social app?) Say you’re a…

SQL校驗優化

我的思路只能查當前的&#xff1a; ----校驗此行訂單是否已導入&#xff0c;若已導入則提示訂單號并Return -- IF EXISTS (SELECT 1 FROM DOC_Order_Header b LEFT JOIN tblData a -- ON -- a.ConsigneeID b.Consig…

nat64 dns64 linux 內核支持,搭建NAT64/DNS6實現IPv4/v6轉換

NAT64采用tayga實現&#xff0c;DNS64采用bind9.8實現。1 平臺搭建平臺為ubuntu12.04 Desktop版本。正常安裝即可。2 NAT64(tayga)2.1 安裝在終端模式下輸入sudo apt-get install tayga2.2 配置2.2.1 相關設置sudo gedit /etc/tayga.conf按照說明配置&#xff0c;目前實現方案不…

React學習筆記(持續更新)

2.2頁面加載過程 1.資源加載過程&#xff1a;URL->DNS查詢->資源請求->瀏覽器解析 ①URL結構&#xff1a;http://www.hhh.com:80/getdata?pid1#title[協議://域名&#xff1a;端口/路徑?參數#哈希] ②DNS查詢&#xff1a;瀏覽器<--&#xff08;ip&#xff09;&am…

2年工作經驗進 初創公司_溝通是關鍵:通過兩家初創公司獲得的成長經驗教訓+找工作...

2年工作經驗進 初創公司by Niki Agrawal通過尼基阿格勞瓦爾(Niki Agrawal) 溝通是關鍵&#xff1a;通過兩家初創公司獲得的成長經驗教訓找工作 (Communication is key: growth lessons learned through two startups a job hunt) It’s been a crazy two years. I founded tw…

Hibernate問題淺析

1、什么是SessionFactory&#xff1f;什么是Session&#xff1f;httpsession和hibernate的session的有什么區別&#xff1f;SessionFactory接口負責初始化Hibernate。它充當數據存儲源的代理&#xff0c;并負責創建Session對象。這里用到了工廠模式。需要注意的是SessionFactor…

Oracle中SQL語句學習五(統計分組語句group by和having)

oracle&#xff08;41&#xff09; 在 應用系統開發中&#xff0c;進行需要統計數據庫中的數據&#xff0c;當執行數據統計時&#xff0c;需要將表中的數據進行分組顯示&#xff0c;在統計分組中是通過group by子句、分組函數、having子句共同實現的。其中group by子句用于指定…

linux系統去吧,要開始另一個linux操作系統的嘗試了,說說我以前的ubuntu吧

我想&#xff0c;除了嘗試一下ubuntu的神奇魅力的同時&#xff0c;我應該去體驗一下RedHat的神奇吧&#xff01;馬上就要告別ubuntu了&#xff0c;我想把我的部分使用經歷和大家分享分享&#xff01;首先&#xff0c;無論是ubuntu8.04、10.04還是10.1的效果都是很好的&#xff…