Python:访问“模块范围” vars [英] Python: accessing "module scope" vars

查看:109
本文介绍了Python:访问“模块范围” vars的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在学习Python,我必须处理Python 2.7项目。

I'm currently learning Python, and I have to work on a Python 2.7 project.

在模块本身的函数中访问模块范围

Accessing "module scope" variables in functions of the module itself is a bit confusing for me, and I didn't succeed in finding a satisfying way.

我的尝试到目前为止:

方式1:

my_module.py

my_module.py

my_global_var = None

def my_func():
    global my_global_var
    my_global_var = 'something_else'

这里我认为混淆本地和模块范围的变量可能很容易。

Here I think that confusing local and "module scope" vars may be quite easy.

2:

my_module.py

my_module.py

import my_module

my_global_var = None

def my_func():
    my_module.my_global_var = 'something_else'

这里,my_module的名称在必要时不能像way 1那样容易改变。另外,将一个模块导入自己听起来很奇怪。

Here, the name of "my_module" could not be as easily changed as "way 1" when necessary. Plus, importing a module into itself sounds quite weird.

你会推荐什么?或者你会建议一些别的?感谢。

What would you recommend? Or would you suggest something else? Thanks.

推荐答案

您可能想阅读 Python的命名空间。方法1是正确的,但一般不必要,从不使用2.一个更简单的方法是只使用dict(或类或其他对象):

You probably want to read up on Python's namespaces. Way 1 is correct but generally unnecessary, never use 2. An easier approach is to just use a dict (or class or some other object):

my_globals = {'var': None}

def my_func():
    my_globals['var'] = 'something else'

分配始终位于最内层范围,最内层范围始终首先搜索,因此需要全局关键字。在这种情况下,您没有分配到名称,因此没有必要。

Assignments always go into the innermost scope and the innermost scope is always searched first, thus the need for the global keyword. In this case you aren't assigning to a name, so it's unnecessary.

这篇关于Python:访问“模块范围” vars的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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