Javascript 如何访问python3中的上限值?
在JavaScript中,此代码返回4: 设x=3; 让foo==>{ console.logx; } let bar==>{ x=4; 傅; } 酒吧 要分配给全局x,您需要在bar函数中声明全局x。使用全局关键字Javascript 如何访问python3中的上限值?,javascript,python,python-3.x,scope,Javascript,Python,Python 3.x,Scope,在JavaScript中,此代码返回4: 设x=3; 让foo==>{ console.logx; } let bar==>{ x=4; 傅; } 酒吧 要分配给全局x,您需要在bar函数中声明全局x。使用全局关键字 x = 3 def foo: global x x = 4 print(x) foo() 很明显,程序、机器正在映射工作 bar() # in bar function you have x, but python takes it as a priv
x = 3
def foo:
global 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接受一个参数
或
在你们的酒吧里使用全局,这样机器就会明白酒吧里的x是全局x,而不是私有的
如果变量名在全局范围内定义,并且在函数的局部范围内使用,则会发生两种情况: 您正在进行一个读取操作示例:只需打印它,那么变量引用的值与全局对象相同 您正在进行一个写操作示例:为变量赋值,然后在函数的局部作用域中创建一个新对象,并引用它。这不再指向全局对象 但是,如果要使用全局范围中的变量并在局部范围内对其进行写操作,则需要将其声明为全局变量
这回答了你的问题吗?可能重复:我不想分配全局x,因为我不想覆盖顶级作用域x。我想在bar范围内覆盖x。@brachkoff我不想覆盖top范围x-但JavaScript部分就是这样做的。
def bar():
x = 4
foo(x)
def foo(args):
print(args)
# OUTPUT
# >>> 4
def bar():
# here machine understands that this is global variabl
# not the private one
global x = 4
foo()
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
x = 3
def bar():
global x
x = 4
bar()
# Both x points to the same int object