首页 > 编程语言 > 详细

python 方法中的变量与self.变量的区别

时间:2020-08-30 15:48:25      阅读:77      评论:0      收藏:0      [点我收藏+]

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

 

python 方法中的变量与self.变量的区别

原文:https://www.cnblogs.com/xdd1997/p/13585295.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!