Skip to main content
 首页 » 编程设计

python之谁能帮我理解 Python 变量作用域

2025年05月04日13wuhuacong

我编写了一个如下所示的测试程序:

#!/usr/bin/python 
 
def incrementc(): 
    c = c + 1 
 
def main(): 
    c = 5 
    incrementc() 
 
main() 
 
print c 

我想,因为我在 main 的主体中调用了 incrementc,所以来自 main 的所有变量都会传递给 incrementc。但是当我运行这个程序时,我得到了

Traceback (most recent call last): 
  File "test.py", line 10, in <module> 
    main() 
  File "test.py", line 8, in main 
    incrementc() 
  File "test.py", line 4, in incrementc 
    c = c + 1 
UnboundLocalError: local variable 'c' referenced before assignment 

为什么c没有通过?而如果我想让一个变量被多个函数引用,是否必须要全局声明呢?我在某处读到全局变量不好。

谢谢!

请您参考如下方法:

您正在考虑 dynamic scoping .动态作用域的问题在于 incrementc 的行为将取决于之前的函数调用,这使得对代码进行推理变得非常困难。相反,大多数编程语言(包括 Python)使用静态范围:c 仅在 main 中可见。

要完成您想要的,您可以使用全局变量,或者更好的是,将 c 作为参数传递。现在,因为 Python 中的原语是不可变的,传递的整数不能更改(它实际上是按值传递的),因此您必须将它打包到一个容器中,例如列表。像这样:

def increment(l): 
    l[0] = l[0] + 1 
 
def main(): 
    c = [5] 
    increment(c) 
    print c[0] 
 
main() 

或者,更简单:

def increment(l): 
    return l + 1 
 
def main(): 
    c = 5 
    print increment(c) 
 
main() 

一般来说,全局变量是不好的,因为它们很容易编写难以理解的代码。如果您只有这两个函数,您可以继续将 c 设为全局,因为代码的作用仍然很明显。如果您有更多代码,最好将变量作为参数传递;这样你就可以更容易地看到谁依赖于全局变量。