gpt4 book ai didi

python - python中的局部/全局变量混淆

转载 作者:太空宇宙 更新时间:2023-11-03 13:20:58 26 4
gpt4 key购买 nike

<分区>

Possible Duplicate:
referenced before assignment error in python

我在 python 中遇到了一个奇怪的错误。以下 ipython 日志对其进行了总结:

In [10]: def confused(stuff):
....: print huh
....: return stuff
....:

In [11]: confused(87)
0
Out[11]: 87

In [12]: def confused(stuff):
....: print huh
....: huh += 1
....: return stuff
....:

In [13]: confused(9)
---------------------------------------------------------------------------
UnboundLocalError Traceback (most recent call last)
/home/max/verk/btr-email/build/x86_64/bin/ipython in <module>()
----> 1 confused(9)

/home/max/verk/btr-email/build/x86_64/bin/ipython in confused(stuff)
1 def confused(stuff):
----> 2 print huh
3 huh += 1
4 return stuff

UnboundLocalError: local variable 'huh' referenced before assignment

有效函数和抛出错误的函数之间的唯一区别是 +=1 行,即便如此,它也会在之前有效的行上抛出错误!如果我在方法的第二个版本中引用 huh 之前放置 global huh,它也不会抛出错误。

为什么在我向变量添加 1 的地方添加一行突然将其从全局变量更改为局部变量?

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com