外部范围的阴影名称 xyz

Shadows name xyz from outer scope(外部范围的阴影名称 xyz)

本文介绍了外部范围的阴影名称 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

基础教程推荐