UnboundLocalError

It can be a surprise to get the UnboundLocalError in previously working code when it is modified by adding an assignment statement somewhere in the body of a function.

在一个函数内部的某个地方,对一个变量通过赋值来修改的时候,遇到UnboundLocalError是让人非常吃惊的。

This code:

例如下面的代码:

>>> x = 10
>>> def bar():
...     print x
>>> bar()
10

works, but this code:

运行成功,但是再往下看:

>>> x = 10
>>> def foo():
...     print x
...     x += 1

results in an UnboundLocalError:

出现了UNboundLocalError的错误:(有点意思的是,这个出错的地方是 print x 这行代码)

>>> foo()
Traceback (most recent call last):
  ...
UnboundLocalError: local variable 'x' referenced before assignment

This is because when you make an assignment to a variable in a scope, that variable becomes local to that scope and shadows any similarly named variable in the outer scope. Since the last statement in foo assigns a new value to x, the compiler recognizes it as a local variable. Consequently when the earlier print x attempts to print the uninitialized local variable and an error results.

这是由于在一个范围内,对一个变量进行赋值,这个变量变成该范围内的局部变量,会首先调用这个变量(而不会调用外部的相同变量名的变量),由于foo函数中最后一行代码对x赋了一个新值,编译器认为这是一个局部变量。因而,在之前对x尝试进行print的时候,会认为这是在print一个未被初始化的对象,所以出现了一个错误。

In the example above you can access the outer scope variable by declaring it global:

在上面的那个例子中,你可以将变量声明为global(全局变量)来对外部变量进行打印和修改

>>> x = 10
>>> def foobar():
...     global x
...     print x
...     x += 1
>>> foobar()
10

This explicit declaration is required in order to remind you that (unlike the superficially analogous situation with class and instance variables) you are actually modifying the value of the variable in the outer scope:

这个明显的声明是需要的:用来提醒你,你在修改外部变量的值

>>> print x
11
  • 3
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值