這段代碼我覺得很好的說明了python中類的方法在加self和不加self的區別。
>>> class AAA(object): ... def go(self): ... self.one = 'hello' ... >>> class BBB(object): ... def go(self): ... one = 'hello' ... >>> a1 = AAA() >>> a1.go() >>> a1.one 'hello' >>> a2 = AAA() >>> a2.one Traceback (most recent call last): File "<stdin>", line 1, in <module> AttributeError: 'AAA' object has no attribute 'one' >>> a2.go() >>> a2.one 'hello' >>> b1 = BBB() >>> b1.go() >>> b1.one Traceback (most recent call last): File "<stdin>", line 1, in <module> AttributeError: 'BBB' object has no attribute 'one' >>> BBB.one Traceback (most recent call last): File "<stdin>", line 1, in <module> AttributeError: type object 'BBB' has no attribute 'one' >>> class BBB(object): ... def go(self): ... one = 'hello' ... print one ... self.another = one ... >>> b2 = BBB() >>> b2.go() hello >>> b2.another 'hello' >>> b2.one Traceback (most recent call last): File "<stdin>", line 1, in <module> AttributeError: 'BBB' object has no attribute 'one'
個人認爲方法中加self的變量可以看成是類的屬性,或者是特性。使用方法改變和調用屬性,屬性改變實例的狀態。方法中不加self的變量可以看成一個局部變量,該變量不能被直接引用。
類本身的局部變量(個人的認爲定義在方法以外不以self開頭的變量是類本身的局部變量)是可以被直接掉用的,注意這裏不是指上面所說的方法內的局部變量(這兩個命名空間不同)。如果方法中有有變量與類的局部變量同名,那麼方法中的局部變量將會屏蔽類中的局部變量即類中的局部變量不在起作用。
本文純屬個人簡介,如有錯誤的地方,感謝指出。
本文代碼來自:https://gist.github.com/hahastudio/9304929#file-gistfile1-py