擅长:python、mysql、java
<p>当您在sample_func内时,主函数的if分支内的代码实际上在作用域内。您可以从变量<code>x</code>中读取(尝试一下)。这没关系,因为你并不真正关心它,所以你有几个选择前进。</p>
<p>1)禁用pycharm中的阴影警告。老实说,这是最直接的,这取决于你对程序员的经验,这可能是最有意义的(如果你是相对较新的,我不会这样做,虽然)</p>
<p>2)将主代码放入主函数中。这可能是任何生产级代码的最佳解决方案。Python非常擅长按照您想要的方式来做事情,因此您应该小心不要落入陷阱。如果你正在构建一个模块,在模块级拥有大量的逻辑会让你陷入困境。相反,以下内容可能会有所帮助:</p>
<pre><code>def main():
# Note, as of python 2.7 the interpreter became smart enough
# to realize that x is defined in a loop, so printing x on this
# line (prior to the for loop executing) will throw an exception!
# However, if you print x by itself without the for loop it will
# expose that it's still in scope. See https://gist.github.com/nedrocks/fe42a4c3b5d05f1cb61e18c4dabe1e7a
for x in range(1, 5):
sample_func()
if __name__ == '__main__':
main()
</code></pre>
<p>3)不要使用与在更大范围内使用的变量名相同的变量名。这很难执行,而且有点与1相反。</p>