我在理解变量范围时遇到一些问题。对于普通变量,我理解这一点,但是如果我定义一个对象,那么事情会使我感到困惑。请看下面的代码:
class test():
pass
text="hi there"
num=1
p=test()
p.var="good bye"
p.arr = []
p.num = 5
def output_before():
print "before change: object text " ,p.var
print "before change: object number ", p.num
print "before change: basic text " ,text
print "before change: basic num ", num
def output_after():
print "after change: object text " ,p.var
print "after change: object number ", p.num
print "after change: basic text " ,text
print "after change: basic num ", num
def change():
text = "whats up"
num=5
p.num=10
p.var="good night"
p.arr.append ("sleep well")
output_before()
change()
output_after()
print p.arr
for i in range(5):
change()
print p.arr
这给了我这个输出:
before change: object text good bye
before change: object number 5
before change: basic text hi there
before change: basic num 1
after change: object text good night
after change: object number 10
after change: basic text hi there
after change: basic num 1
['sleep well']
['sleep well', 'sleep well', 'sleep well', 'sleep well', 'sleep well', 'sleep well']
默认情况下,来自类测试的对象似乎是全局的。这是正确的吗 ?
慕码人2483693
汪汪一只猫
人到中年有点甜
相关分类