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开头的变量是类本身的局部变量)是可以被直接掉用的,注意这里不是指上面所说的方法内的局部变量(这两个命名空间不同)。如果方法中有有变量与类的局部变量同名,那么方法中的局部变量将会屏蔽类中的局部变量即类中的局部变量不在起作用。


转载仅为学习,不会商用。
欢迎转载原创,附文链接。
原文地址:https://www.cnblogs.com/xdd1997/p/13585295.html