In this post, we will see about error 分配前引用的局部变量
在 蟒蛇.
问题
让 me explain this error with the help of an example.
1 2 3 4 5 6 7 |
a = 100 定义 增量A(): a=a+5 返回 a 打印(“ a的值:”,增量A()) |
当您运行上述程序时,将获得以下输出:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
-------------------------------------- UnboundLocalError 追溯 (最 最近 呼叫 持续) <ipython的-输入-89-c87da0a8ced6> 在 <模组> 3 a=a+5 4 返回 a --> 5 打印(“ a的值:”,增量A()) <ipython的-输入-89-c87da0a8ced6> 在 增量A() 1 a = 100 2 定义 增量A(): --> 3 a=a+5 4 返回 a 5 打印(“ a的值:”,增量A()) UnboundLocalError: 本地 变量 '一个' 被引用 之前 分配 |
让’s understand why we are getting this error UnboundLocalError
.
当Python解释器解析任何函数定义并找到任何赋值时,例如
1 2 3 |
a = |
蟒蛇 在 terpreter treats a
as 本地 变量 by 定义ault.
Since a
is considered as 本地 变量, when python executes
1 2 3 |
a=a+5 |
it evaluates right-hand side first and tries to find value of 变量 a
. It finds a
first time, hence raised this error: UnboundLocalError: 本地 变量 被引用 之前 分配
解
使用全局
要解决此问题,您需要显式声明一个全局变量,它将解决此问题。
让’在我们的程序中实现此解决方案。
1 2 3 4 5 6 7 8 |
a = 100 定义 增量A(): 全球 a a=a+5 返回 a 打印(“ a的值:”,增量A()) |
当您运行上述程序时,将获得以下输出:
As you can see, after declaring 全球 a
在 增量A()
function, we solved this issue.
💡 你知道吗?
请注意,如果您不’不要将赋值与变量一起使用,您将赢得’t get this error.
123456 a = 100定义 增量A():返回 a打印(“ a的值:”,增量A())当您运行上述程序时,将获得以下输出:
a的值:100如果您使用直接分配而不使用变量,那么您也将赢得’t get this error.
1234567 a = 100定义 增量A():a=200返回 a打印(“ a的值:”,增量A())当您运行上述程序时,将获得以下输出:
a的价值:200
使用非本地
You can use 非本地
to resolve this issue if you are using nested functions. 非本地
works 在 nested functions and generally used when 变量 should not belong to 在 ner function.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
a = 100 定义 增量A(): a = 200 定义 增量ABy10(): #将代表a = 200 非本地 a a=a+10 打印(“内部函数的值:”,a) 增量ABy10() a=a+5 返回 a 打印(“ a的值:”,增量A()) |
输出:
a的价值:215
When we use 非本地
, it refers value from nearest enclosing scope.
让’s change 非本地
to 全球
and you will be able to understand the difference.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
a = 100 定义 增量A(): a = 200 定义 增量ABy10(): #表示a = 100 全球 a a=a+10 打印(“内部函数的值:”,a) 增量ABy10() #将表示为200 a=a+5 返回 a 打印(“ a的值:”,增量A()) |
输出:
a的价值:205
As you can see, value of a
在 side 增量ABy10()
was 100 due to 全球 a
, then it was 在 cremented by 10 and when we used a
在 side 增量A()
, it was 200 as a
is considered 本地 变量 here and then 在 cremented it by 5.
那’关于在Python中赋值之前引用的局部变量的全部内容。