如何访问python3中的上限值?

2024-10-03 04:28:25 发布

您现在位置:Python中文网/ 问答频道 /正文

在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

为什么以及如何运作


Tags: 代码httpslogfoodefbaritjavascript
3条回答

要分配给全局x,需要在bar函数中声明global x

很明显,程序、机器正在映射工作

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

相关问题 更多 >