Python高手进

来源:百度知道 编辑:UC知道 时间:2024/06/19 22:06:56
Consider the following code:
class A:
x = 4
def b(self, c):
x = 6
print x, self.x
self.x = 3
print x, self.x

thing1 = A()
print thing1.x
thing1.b(2)
print thing1.x
thing2 = A()
print thing2.x

The code executes 5 print statements. What does each one print out?
我直接打进python,答案是
1. 4
2. 3
3. 4
4. 3
5. 4
但是第二第三个答案显示错误
麻烦帮忙看看

>>> print thing1.x
4
#一开始x=4,thing1.x==4
>>> thing1.b(2)
6 4
6 3
一开始x=6(thing1.b中的x), 第5行先显示x(方法b中的局部变量),再显示类a的x值(x=4定义,不受x=6影响)
>>> print thing1.x
3
#刚才调用方法b时有"self.x=3"将类a的x从6改变为3
>>> thing2 = a()
#新建一个实例,没有输出
>>> print thing2.x
4
#新的实例当然是x=4啦!

=================
综上,答案是
4
6 4
6 3
3
4

你的缩进都没有,不知道那几个print是定义在哪个层次....

这个题目真白。谁会在实际编程中故意引起名字空间的冲突

constructor