為什么要講 self 參數
class PoloBlog: def __init__(self): ... def say(self): ...
在類里面,所有實例方法都需要加 self 參數,且排在第一個,有且僅有一個
self 參數的含義
在類中定義的方法,第一個參數 self 指向調用該方法的實例對象,在方法中通過 self.屬性 這樣的形式訪問對象的實例屬性
self 參數真的必須叫 self 嗎
- 其實並不是哦
- Python 只是規定,無論是構造方法還是實例方法,最少要包含一個參數,並沒有規定該參數的具體名稱
- 之所以將其命名為 self,只是約定俗成的一種習慣,遵守這個約定,可以使我們編寫的代碼具有更好的可讀性,大家一看到 self,就知道它的作用
- 你想叫 polo 也可以
class test: def __init__(polo): polo.name = "小菠蘿" def test(polo): print(polo.name) t = test() t.test() # 輸出結果 小菠蘿
只是可讀性很差
如何理解 self 參數
類比
- 如果把類比作造房子的圖紙
- 類實例化后的對象是真正可以住的房子
- 根據一張圖紙(類),可以設計出成千上萬的房子(實例對象)
- 每個房子長相都是類似的(都有相同的實例屬性和實例方法),但它們都有各自的主人
- 如何區分不同的房子:通過 self 參數,可以保證每個房子的主任僅能進入自己的房子(每個實例對象只能調用自己的實例屬性和實例方法)
重點
- 一個類可以產生多個實例對象,當某個實例對象調用實例方法,該對象會把自身的引用作為第一個參數自動傳遞給該方法
- 換句話說:Python 會自動將實例方法的第一個參數指向調用該方法的對象
- 這樣,Python 解釋器就知道到底要執行哪個對象的實例方法了
- 調用實例方法的時候,不需要手動為第一個參數傳值
通過代碼了解 self
# self class PoloBlog: def __init__(self): print("構造方法:self is ", self, " self 的 id is ", id(self)) def say(self): print("實例方法:self is ", self, " self 的 id is ", id(self)) # 實例對象一 blog1 = PoloBlog() blog1.say() print("實例對象 blog1 id is ", id(blog1)) # 實例對象2 blog2 = PoloBlog() blog2.say() print("實例對象 blog2 id is ", id(blog2)) # 輸出結果 構造方法:self is <__main__.PoloBlog object at 0x10f884af0> self 的 id is 4555557616 實例方法:self is <__main__.PoloBlog object at 0x10f884af0> self 的 id is 4555557616 實例對象 blog1 id is 4555557616 構造方法:self is <__main__.PoloBlog object at 0x10f884ac0> self 的 id is 4555557568 實例方法:self is <__main__.PoloBlog object at 0x10f884ac0> self 的 id is 4555557568 實例對象 blog2 id is 4555557568
- 很明顯,self 存的就是調用該實例方法的實例對象的引用
- 所以!誰調用實例方法,self 就是誰!
