在JavaScript中,此代码返回4:
let x = 3;
let foo = () => {
console.log(x);
}
let bar = () => {
x = 4;
foo();
}
bar();
但Python3中的相同代码返回3:
x = 3
def foo():
print(x)
def bar():
x = 4
foo()
bar()
https://repl.it/@brachkow/python3scope
为什么以及如何运作
要分配给全局
x
,需要在bar
函数中声明global x
很明显,程序、机器正在映射工作
现在,如果要打印
4
,而不是3
,这是全局的,您需要在foo()中传递私有值,并使foo()接受一个参数或
如果变量名在全局范围内定义,并且在函数的局部范围内使用,则会发生两种情况:
但是,如果要使用全局范围中的变量并在局部范围内对其进行写操作,则需要将其声明为
global
相关问题 更多 >
编程相关推荐