在函数外声明的变量 [英] Variables declared outside function

查看:73
本文介绍了在函数外声明的变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

<块引用>

可能的重复:
在 python 中的赋值错误之前被引用
赋值前引用的本地变量

我只是想看看变量范围是如何工作的,但遇到了以下情况(都是从终端运行的):

x = 1定义公司():x += 5公司()回溯(最近一次调用最后一次):文件<stdin>",第 1 行,在 <module> 中文件<stdin>",第 2 行,incUnboundLocalError:赋值前引用了局部变量x"

我在想,我的方法中可能无法访问 x,所以我尝试了:

def inc():打印(x)1

所以这是有效的.现在我知道我可以这样做:

 def inc():全球 xx += 1

这行得通,但我的问题是为什么第一个例子失败了?我的意思是我希望因为 print(x) 工作 x 在函数内是可见的,所以为什么 x += 5 会失败?

解决方案

与采用真实"词法范围的语言不同,Python 选择为变量设置特定的命名空间",无论它是global非本地,或本地.可以说,让开发人员有意识地使用此类命名空间进行编码更明确,因此更易于理解.我认为这种复杂性使语言更加笨拙,但我想这完全取决于个人喜好.

这里有一些关于global的例子:-

<预><代码>>>>global_var = 5>>>定义 fn():...打印(global_var)...>>>fn()5>>>def fn_2():... global_var += 2...打印(global_var)...>>>fn_2()回溯(最近一次调用最后一次):文件<stdin>",第 1 行,在 <module> 中文件<stdin>",第 2 行,在 fn_2 中UnboundLocalError:赋值前引用了局部变量global_var">>>def fn_3():... 全球 global_var... global_var += 2...打印(global_var)...>>>fn_3()7

同样的模式也可以应用于 nonlocal 变量,但这个关键字只适用于后面的 Python 版本.

如果您想知道,nonlocal 用于变量不是全局变量,但不在它所使用的函数定义内.例如,def 中的 def 很常见,部分原因是缺少多语句 lambda.不过,有一个 hack 可以绕过早期 Python 中缺少此功能的问题,我依稀记得它涉及使用单元素列表...

请注意,写入变量是需要这些关键字的地方.只是从它们中读取并不含糊,因此不需要.除非您的内部 def 使用与外部变量名称相同的变量名,老实说应该避免这样做.

Possible Duplicate:
referenced before assignment error in python
local var referenced before assignment

I was just trying to see how variable scopes work and ran into the following situation (all ran from the terminal):

x = 1
def inc():
    x += 5

inc()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 2, in inc
UnboundLocalError: local variable 'x' referenced before assignment

I was thinking maybe I don't have access to x in my method, so I tried:

def inc():
    print(x)

1

So this works. Now I know I could just do:

 def inc():
     global x
     x += 1

And this would work, but my question is why does the first example fail? I mean I would expect since print(x) worked that x is visible inside the function so why would the x += 5 fail?

解决方案

Unlike languages that employ 'true' lexical scoping, Python opts to have specific 'namespaces' for variables, whether it be global, nonlocal, or local. It could be argued that making developers consciously code with such namespaces in mind is more explicit, thus more understandable. I would argue that such complexities make the language more unwieldy, but I guess it's all down to personal preference.

Here are some examples regarding global:-

>>> global_var = 5
>>> def fn():
...     print(global_var)
... 
>>> fn()
5
>>> def fn_2():
...     global_var += 2
...     print(global_var)
... 
>>> fn_2()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 2, in fn_2
UnboundLocalError: local variable 'global_var' referenced before assignment
>>> def fn_3():
...     global global_var
...     global_var += 2
...     print(global_var)
... 
>>> fn_3()
7

The same patterns can be applied to nonlocal variables too, but this keyword is only available to the latter Python versions.

In case you're wondering, nonlocal is used where a variable isn't global, but isn't within the function definition it's being used. For example, a def within a def, which is a common occurrence partially due to a lack of multi-statement lambdas. There's a hack to bypass the lack of this feature in the earlier Pythons though, I vaguely remember it involving the use of a single-element list...

Note that writing to variables is where these keywords are needed. Just reading from them isn't ambiguous, thus not needed. Unless you have inner defs using the same variable names as the outer ones, which just should just be avoided to be honest.

这篇关于在函数外声明的变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆