在JavaScript中,此代码返回4:
null
let x = 3;
let foo = () => {
console.log(x);
}
let bar = () => {
x = 4;
foo();
}
bar();
null
但Python3中的相同代码返回3:
x = 3
def foo():
print(x)
def bar():
x = 4
foo()
bar()
https://repl./@brachkow/python3scope
为什么和如何工作?
要分配给全局x
,您需要在bar
函数中声明全局x
。
使用全局关键字
x=3 def foo:
 ; ; ;全局x
 ; ; ;x=4
 ;print(x)
foo()
很清楚,程序,机器正在工作的映射
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
,而不是3
,后者是全局的,**您需要在foo()中传递私有值,并使foo()接受一个参数
def bar():
args = 4
foo(args)
def foo(args):
print(args)
# OUTPUT
# >>> 4
或
在条()
内使用global
,以便机器将理解条内的x
是全局x,而不是私有
def bar():
# here machine understands that this is global variabl
# not the private one
global x = 4
foo()