Python 自由变量。为什么会失败?

2024-02-22

以下代码打印 123:

>>> a = 123
>>> def f():
...     print a
...
>>> f()
123
>>>

但以下失败:

>>> a = 123
>>> def f():
...     print a
...     a = 456
...     print a
...
>>> f()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 2, in f
UnboundLocalError: local variable 'a' referenced before assignment
>>>

我本来希望打印出来:

123
456

我在这里缺少什么?

附:如果重要的话,我正在使用 Python 2.6.6。


如果函数仅读取变量,则假定它是全局的。如果函数曾经写入过,则假定它是本地的。在第二个函数中,a 被写入,因此假定它是本地的。那么上面的行(从中读取的行)无效。

以下是 Python 常见问题解答的链接:http://docs.python.org/faq/programming.html#what-are-the-rules-for-local-and-global-variables-in-python http://docs.python.org/faq/programming.html#what-are-the-rules-for-local-and-global-variables-in-python

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Python 自由变量。为什么会失败? 的相关文章

随机推荐