首先明確的是self只有在類的方法中纔會有,獨立的函數或方法是不必帶有self的。self在定義類的方法時是必須有的,雖然在調用時不必傳入相應的參數。
self名稱不是必須的,在python中self不是關鍵詞,你可以定義成a或b或其它名字都可以,但是約定成俗,不要搞另類,大家會不明白的。下例中將self改爲myname一樣沒有錯誤:
1 class Person:
2 def _init_(myname,name):
3 myname.name=name
4 def sayhello(myname):
5 print 'My name is:',myname.name
6 p=Person('Bill')
7 print p
self指的是類實例對象本身(注意:不是類本身)。
1 class Person:
2 def _init_(self,name):
3 self.name=name
4 def sayhello(self):
5 print 'My name is:',self.name
6 p=Person('Bill')
7 print p
在上述例子中,
self
指向Person的實例p。
爲什麼不是指向類本身呢,如下例子:
1 class Person:
2 def _init_(self,name):
3 self.name=name
4 def sayhello(self):
5 print 'My name is:',self.name
6 p=Person('Bill')
7 p1 = Person('Apple')
8 print p
如果self指向類本身,那麼當有多個實例對象時,self指向哪一個呢?
轉自:http://www.cnblogs.com/linuxcat/archive/2012/01/05/2220997.html