Shadows name xyz from outer scope(外部范围的阴影名称 xyz)
问题描述
我正在使用 pycharm
,它列出了与代码相关的所有错误/警告.虽然我了解其中的大多数,但我不确定这个来自外部范围的阴影名称 xyz".有一些关于此的 SO 帖子:隐藏名称有多糟糕在外部范围中定义? 但他们似乎正在访问一个全局变量.
I am using pycharm
and it lists out all the errors/warnings associated with the code. While I understand most of them I am not sure of this one "Shadows name xyz from outer scope". There are a few SO posts regarding this: How bad is shadowing names defined in outer scopes? but then they seem to be accessing a global variable.
在我的例子中,我的 __main__
函数有几个变量名,然后它调用另一个函数 sample_func
再次使用这些变量名(主要是循环变量名).我假设因为我在不同的函数中,这些变量的范围将是本地的,但是警告似乎暗示了其他情况.
In my case, my __main__
function has a few variable names and then it is calling another function sample_func
which uses those variable names again (primarily the loop variable names). I am assuming because I am in a different function, the scope for these variables will be local, however the warning seem to suggest otherwise.
有什么想法吗?这里有一些代码供您参考:
Any thoughts? For your reference here is some code:
def sample_func():
for x in range(1, 5): --> shadows name x from outer scope
print x
if __name__ == "__main__":
for x in range(1, 5):
sample_func()
推荐答案
警告是关于您在内部范围内重新使用这些名称所引入的潜在危险.它可能会导致您错过一个错误.例如,考虑这个
The warning is about the potential danger you are introducing by re-using these names at inner scopes. It can cause you to miss a bug. For example, consider this
def sample_func(*args):
smaple = sum(args) # note the misspelling of `sample here`
print(sample * sample)
if __name__ == "__main__":
for sample in range(1, 5):
sample_func()
因为您使用了相同的名称,所以您在函数内部的拼写错误不会导致错误.
Because you used the same name, your misspelling inside the function does not cause an error.
当您的代码非常简单时,您将摆脱这种类型的事情而不会产生任何后果.但是最好使用这些最佳实践"以避免在更复杂的代码上出错.
When your code is very simple, you will get away with this type of thing with no consequences. But it's good to use these "best practices" in order to avoid mistakes on more complex code.
这篇关于外部范围的阴影名称 xyz的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:外部范围的阴影名称 xyz


基础教程推荐
- Kivy 使用 opencv.调整图像大小 2022-01-01
- Python,确定字符串是否应转换为 Int 或 Float 2022-01-01
- 在 Django Admin 中使用内联 OneToOneField 2022-01-01
- Python 中是否有任何支持将长字符串转储为块文字或折叠块的 yaml 库? 2022-01-01
- 对多索引数据帧的列进行排序 2022-01-01
- 在 Python 中将货币解析为数字 2022-01-01
- kivy 应用程序中的一个简单网页作为小部件 2022-01-01
- 究竟什么是“容器"?在蟒蛇?(以及所有的 python 容器类型是什么?) 2022-01-01
- 比较两个文本文件以找出差异并将它们输出到新的文本文件 2022-01-01
- matplotlib 设置 yaxis 标签大小 2022-01-01