Python編寫類的時候,每個函數第一個參數都是self。后來對Python越來越熟悉,再回頭看self的概念,慢慢就明白了。
谷歌上有一段解釋很到位,貼出來給大家:
self represents the instance of the class. By using the "self" keywork we can access the attributes and methods of the class in python. It binds the attributes with the given arguments. self is parameter in function and user can use another parameter name in place of it.
意思就是:self 代表了類的實例。 通過使用關鍵字"self", 我們可以獲取類的特性和方法。它將屬性與給定參數綁定。self名稱不是必須的,在python中self不是關鍵詞,你可以定義成a或b或其他名字都可以,但是約定俗成,不要搞另類,大家會不明白的。
首先明確的是self只有在類的方法中才會有,獨立的函數或方法不必帶有self的。self在定義類的方法時是必須有的,雖然在調用時不必傳入相應的參數。
self指的是類實例對象本身(注意:不是類本身)。 以下是一個列子
總結:
self在定義類時需要定義, 但是在調用時會自動傳入。
self的名字並不是規定死的,但最好還是按照約定用self
self總是指調用是的類實例對象