python 方法中的變量與self.變量的區別


原創鏈接:暫未找到
轉載鏈接:Python 方法中變量加self和不加的區別

這段代碼我覺得很好的說明了python中類的方法在加self和不加self的區別。

 

 1 >>> class AAA(object):
 2 ...     def go(self):
 3 ...         self.one = 'hello'
 4 ...
 5 >>> class BBB(object):
 6 ...     def go(self):
 7 ...         one = 'hello'
 8 ...
 9 >>> a1 = AAA()
10 >>> a1.go()
11 >>> a1.one
12 'hello'
13 >>> a2 = AAA()
14 >>> a2.one
15 Traceback (most recent call last):
16   File "<stdin>", line 1, in <module>
17 AttributeError: 'AAA' object has no attribute 'one'
18 >>> a2.go()
19 >>> a2.one
20 'hello'
21 >>> b1 = BBB()
22 >>> b1.go()
23 >>> b1.one
24 Traceback (most recent call last):
25   File "<stdin>", line 1, in <module>
26 AttributeError: 'BBB' object has no attribute 'one'
27 >>> BBB.one
28 Traceback (most recent call last):
29   File "<stdin>", line 1, in <module>
30 AttributeError: type object 'BBB' has no attribute 'one'
31 >>> class BBB(object):
32 ...     def go(self):
33 ...         one = 'hello'
34 ...         print one
35 ...         self.another = one
36 ...
37 >>> b2 = BBB()
38 >>> b2.go()
39 hello
40 >>> b2.another
41 'hello'
42 >>> b2.one
43 Traceback (most recent call last):
44   File "<stdin>", line 1, in <module>
45 AttributeError: 'BBB' object has no attribute 'one'

 

個人認為方法中加self的變量可以看成是類的屬性,或者是特性。使用方法改變和調用屬性,屬性改變實例的狀態。方法中不加self的變量可以看成一個局部變量,該變量不能被直接引用。

 

類本身的局部變量(個人的認為定義在方法以外不以self開頭的變量是類本身的局部變量)是可以被直接掉用的,注意這里不是指上面所說的方法內的局部變量(這兩個命名空間不同)。如果方法中有有變量與類的局部變量同名,那么方法中的局部變量將會屏蔽類中的局部變量即類中的局部變量不在起作用。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM