为什么在Python的循环外可以访问变量? [英] Why a variable can be accessible outside the loop in Python?

查看:225
本文介绍了为什么在Python的循环外可以访问变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请考虑以下示例:

for iter in xrange(10):
   myvar = iter

print myvar
# 9

myvar显然在循环之外吗?但是它仍然可以访问. 如果是Perl,则会抛出错误.

Here myvar is clearly outside the loop? But it is still accessible. If this is Perl, it will throw an error.

Python中这种功能背后的原因是什么? 有害吗?那么,在循环之前声明变量的最佳实践是什么?

What's the reason behind such feature in Python? Is it harmful? What's the best practice then, to declare a variable before looping?

推荐答案

for循环没有创建新的作用域(Ruby的行为也相同).如果您来自为块创建新作用域的语言,这可能会令人惊讶.

There is no new scope created by the for loop (Ruby also behaves the same way). This may be surprising if you are coming from a language that creates new scopes for blocks.

只要您知道规则,我就认为这没有害处.

I don't believe it's harmful as long as you know the rules.

如果您的函数和方法太大,以至于无法跟踪,那么您的函数和方法就太大了.

If your functions and methods are so large that you have trouble keeping track, then your functions and methods are too large.

这篇关于为什么在Python的循环外可以访问变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆