gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 07:03:38 25 4
gpt4 key购买 nike

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

#!/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 设为全局,因为代码的作用仍然很明显。如果您有更多代码,最好将变量作为参数传递;这样你就可以更容易地看到谁依赖于全局变量。

关于python - 谁能帮我理解 Python 变量作用域?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7047133/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com