4 回答
TA贡献1859条经验 获得超6个赞
如果在全局范围内定义的变量名称也在函数的局部范围内使用,则会发生两件事:
您正在进行读取操作(例如:简单地打印它),那么变量引用的值与全局对象相同
x = 3
def foo():
print(x)
foo()
# Here the x in the global scope and foo's scope both point to the same int object
您正在进行写操作(示例:为变量赋值),然后在函数的局部范围内创建一个新对象并引用它。这不再指向全局对象
x = 3
def bar():
x = 4
bar()
# Here the x in the global scope and bar's scope points to two different int objects
但是,如果你想在全局范围内使用一个变量并想在局部范围内对其进行写操作,你需要将它声明为global
x = 3
def bar():
global x
x = 4
bar()
# Both x points to the same int object
TA贡献1835条经验 获得超7个赞
很明显,程序,机器在映射中工作
bar()
# in bar function you have x, but python takes it as a private x, not the global one
def bar():
x = 4
foo()
# Now when you call foo(), it will take the global x = 3
# into consideration, and not the private variable [Basic Access Modal]
def foo():
print(x)
# Hence OUTPUT
# >>> 3
现在,如果你想打印4, not 3,这是全局的,你需要在 foo() 中传递私有值,并使 foo() 接受一个参数
def bar():
x = 4
foo(x)
def foo(args):
print(args)
# OUTPUT
# >>> 4
或者
global在你的内部使用bar(),这样机器就会明白xbar 的内部是全局 x,而不是私有的
def bar():
# here machine understands that this is global variabl
# not the private one
global x = 4
foo()
添加回答
举报