【问题标题】:Global variables and NameError in Python [duplicate]Python中的全局变量和NameError [重复]
【发布时间】:2021-08-02 07:56:13
【问题描述】:

以下程序给了我错误:

NameError: name 'n' is not defined

def g():
    n=7
    def f():
        global n
        if n==7:
            n=7
    return f()
g()

谁能帮我理解这是什么意思?

【问题讨论】:

  • n 实际上应该是全球性的吗?因为它看起来更像是 g 的局部变量,这将使它成为 f 中的 nonlocal,而不是全局变量。见stackoverflow.com/q/2609518/38906320
  • 这就是它所说的,当你点击if n==7这一行时没有全局定义的n。在这种情况下,请使用nonlocal

标签: python global-variables nameerror


【解决方案1】:

在您的 g() 函数中插入一个全局变量。

def g():
    global n
    n=7
    def f():
        global n
        if n==7:
            n=7
    return f()
g()

当这种情况发生时,一个更简化的版本是这样的。

n = 10
def g():
    n+=1
g()

您现在无法修改 n。但是如果我们像这样在函数内部添加全局

n = 10
def g():
    global n
    n+=1
g()
print(n)

我们得到预期的输出

11

但要记住的一件事是,如果我们所做的只是打印变量,我们就不必添加全局变量。

【讨论】:

  • 你应该在这里使用nonlocal,而不是global
【解决方案2】:

有点笼统:不要这样做
..并尝试使您的范围尽可能明显!

这通常是新类或dict(在全局范围内创建时已经是全局且可变的)的情况

shared = {}

def a():
    shared['x'] = 5
    def inner():
        if shared.get('x') == 5:
            shared['x'] = 6
        print(shared['x'])
    inner()

a()
% python3 test.py
6

问题是global n 指的是全局范围,而不是g 的范围(f 已经可以访问,除非它修改了n

这可能会导致一些令人惊讶的结果

#!/usr/bin/env python3
# test.py
def a():
    x = 1
    def display():
        print(x)
    display()

def b():
    x = 1
    def display():
        print(x)
        x = 1
    display()

a()
b()
% python3 test.py
1
Traceback (most recent call last):
  File "test.py", line 17, in <module>
  File "test.py", line 14, in b
  File "test.py", line 12, in display
UnboundLocalError: local variable 'x' referenced before assignment

【讨论】:

  • 不,使用nonlocal
  • @juanpa.arrivillaga “哦,糟糕”;完全有效的使用(实际上对我来说是新的,despite being new in 3.0 - 谢谢!).. 但我真的希望这个答案的核心是,使用关键字来澄清它应该被认为是不正确的潜在混淆范围!
猜你喜欢
  • 1970-01-01
  • 2015-08-19
  • 1970-01-01
  • 2022-01-28
  • 2020-03-31
  • 2012-06-28
  • 1970-01-01
  • 2014-01-14
  • 1970-01-01
相关资源
最近更新 更多