- android - 多次调用 OnPrimaryClipChangedListener
- android - 无法更新 RecyclerView 中的 TextView 字段
- android.database.CursorIndexOutOfBoundsException : Index 0 requested, 光标大小为 0
- android - 使用 AppCompat 时,我们是否需要明确指定其 UI 组件(Spinner、EditText)颜色
我编写了一个如下所示的测试程序:
#!/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/
今天有小伙伴给我留言问到,try{...}catch(){...}是什么意思?它用来干什么? 简单的说 他们是用来捕获异常的 下面我们通过一个例子来详细讲解下
我正在努力提高网站的可访问性,但我不知道如何在页脚中标记社交媒体链接列表。这些链接指向我在 facecook、twitter 等上的帐户。我不想用 role="navigation" 标记这些链接,因
说现在是 6 点,我有一个 Timer 并在 10 点安排了一个 TimerTask。之后,System DateTime 被其他服务(例如 ntp)调整为 9 点钟。我仍然希望我的 TimerTas
就目前而言,这个问题不适合我们的问答形式。我们希望答案得到事实、引用资料或专业知识的支持,但这个问题可能会引发辩论、争论、投票或扩展讨论。如果您觉得这个问题可以改进并可能重新打开,visit the
我就废话不多说了,大家还是直接看代码吧~ ? 1
Maven系列1 1.什么是Maven? Maven是一个项目管理工具,它包含了一个对象模型。一组标准集合,一个依赖管理系统。和用来运行定义在生命周期阶段中插件目标和逻辑。 核心功能 Mav
我是一名优秀的程序员,十分优秀!