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