-
慕斯709654
要分配给 global x,您需要global x在bar函数中声明。
-
慕丝7291255
如果在全局范围内定义的变量名称也在函数的局部范围内使用,则会发生两件事:您正在进行读取操作(例如:简单地打印它),那么变量引用的值与全局对象相同x = 3def foo(): print(x)foo()# Here the x in the global scope and foo's scope both point to the same int object您正在进行写操作(示例:为变量赋值),然后在函数的局部范围内创建一个新对象并引用它。这不再指向全局对象x = 3def bar(): x = 4bar()# Here the x in the global scope and bar's scope points to two different int objects但是,如果你想在全局范围内使用一个变量并想在局部范围内对其进行写操作,你需要将它声明为globalx = 3def bar(): global x x = 4bar()# Both x points to the same int object
-
qq_花开花谢_0
很明显,程序,机器在映射中工作bar()# in bar function you have x, but python takes it as a private x, not the global onedef 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()
-
交互式爱情
使用全局关键字x = 3def foo: global x x = 4 print(x)foo()