Python 方法中变量加self和不加的区别

这段代码我觉得很好的说明了python中类的方法在加self和不加self的区别。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
>>>  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开头的变量是类本身的局部变量)是可以被直接掉用的,注意这里不是指上面所说的方法内的局部变量(这两个命名空间不同)。如果方法中有有变量与类的局部变量同名,那么方法中的局部变量将会屏蔽类中的局部变量即类中的局部变量不在起作用。



评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值