这段代码我觉得很好的说明了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.oneTraceback
(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.oneTraceback
(most recent call last): File "<stdin>",
line 1, in <module>AttributeError: 'BBB' object has
no attribute 'one'>>>
BBB.oneTraceback
(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.oneTraceback
(most recent call last): File "<stdin>",
line 1, in <module>AttributeError: 'BBB' object has
no attribute 'one' |
本文通过示例对比了Python中类的方法内加self与不加self的区别,解释了属性和局部变量的作用域及如何使用。
1034

被折叠的 条评论
为什么被折叠?



