如何在 python 中创建新的作用域 [英] How can one create new scopes in python

查看:34
本文介绍了如何在 python 中创建新的作用域的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在许多语言(和地方)中,通过创建像 这个.

In many languages (and places) there is a nice practice of creating local scopes by creating a block like this.

void foo()
{
     ... Do some stuff ...

     if(TRUE)
     {
         char a;
         int b;

         ... Do some more stuff ...
     }

     ... Do even more stuff ...
 }

如何在 python 中实现这一点而不出现意外的缩进错误并且不使用某种 如果为真:技巧

How can I implement this in python without getting the unexpected indent error and without using some sort of if True: tricks

推荐答案

在 Python 中,作用域分为三种类型:全局、局部和类.您可以创建专门的范围"字典以传递给 exec/eval().此外,您可以使用嵌套范围(在另一个中定义一个函数).我发现这些在我所有的代码中都足够了.

In Python, scoping is of three types : global, local and class. You can create specialized 'scope' dictionaries to pass to exec / eval(). In addition you can use nested scopes (defining a function within another). I found these to be sufficient in all my code.

正如 Douglas Leeder 已经说过的,在其他语言中使用它的主要原因是变量作用域,而这在 Python 中并没有真正发生.此外,Python 是我用过的最易读的语言.做一些像 if-true 技巧(你说你想避免)这样的事情会违背可读性.在这种情况下,我认为最好的办法是将您的代码重构为多个函数,或者使用单个作用域.我认为 Python 中的可用范围足以涵盖所有可能发生的情况,因此本地范围界定不应该真的是必要的.

As Douglas Leeder said already, the main reason to use it in other languages is variable scoping and that doesn't really happen in Python. In addition, Python is the most readable language I have ever used. It would go against the grain of readability to do something like if-true tricks (Which you say you want to avoid). In that case, I think the best bet is to refactor your code into multiple functions, or use a single scope. I think that the available scopes in Python are sufficient to cover every eventuality, so local scoping shouldn't really be necessary.

我希望这会有所帮助.

这篇关于如何在 python 中创建新的作用域的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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