如何访问 python3 中的上限值?

How to access upper scope value in python3?

在JavaScript这段代码中returns4:

let x = 3;

let foo = () => {
  console.log(x);
}

let bar = () => {
  x = 4;
  foo();
}

bar();

但 Python3 returns 中的相同代码 3:

x = 3

def foo():
  print(x)

def bar():
  x = 4
  foo()

bar()

https://repl.it/@brachkow/python3scope

为什么以及如何运作?

要分配给全局 x,您需要在 bar 函数中声明 global 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 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():
  x = 4
  foo(x)

def foo(args):
   print(args)

# OUTPUT
# >>> 4

Use global inside your bar(), so that machine will understand that x inside in bar, is global x, not private

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

但是,如果你想在全局范围内使用一个变量并且想在局部范围内对其进行写操作,你需要将其声明为global

x = 3

def bar():
  global x
  x = 4

bar()

# Both x points to the same int object