<分区>
counter = 0
def addCounter():
counter = counter + 1
return counter
UnboundLocalError: local variable 'counter' referenced before assignment.
每次运行此函数时,我都会尝试进行计数器计数。我也尝试过将计数器变量作为参数传递,但这也不起作用。
标签 python python-3.x
<分区>
counter = 0
def addCounter():
counter = counter + 1
return counter
UnboundLocalError: local variable 'counter' referenced before assignment.
每次运行此函数时,我都会尝试进行计数器计数。我也尝试过将计数器变量作为参数传递,但这也不起作用。
最佳答案
你需要:
counter = 0
def addCounter():
global counter
counter = counter + 1
return counter
说明:在 Python 中,内部变量的声明是隐式的,赋值会自动声明左侧的值,但是该声明始终在局部范围内。这就是为什么如果你这样写:
counter = 0
def addCounter():
return counter
它会工作正常,但只要你添加一个作业
counter = 0
def addCounter():
counter += 1
return counter
它中断了:赋值添加了一个隐式本地声明。 global
覆盖了这个,虽然它要求全局变量事先存在,但它不会创建一个全局变量,它只是告诉函数这是一个全局变量,它可以重新分配给它。
I've tried passing the counter variable in as a parameter as well, but that doesn't work either.
确实不是。 Python 的求值策略有时被称为“共享传递”(或“按值传递引用”),从技术上讲是“按值传递”,但这个术语有点令人困惑,因为在这种情况下,值是引用,引用被复制,但引用的对象不是,因此最终行为与“按值传递”预期的正常预期不同。
关于Python:如何使用函数递增全局变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59836887/