访问“模块范围"变量 [英] accessing "module scope" vars

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

问题描述

我目前正在学习 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'

赋值总是进入最里面的作用域,最里面的作用域总是先被搜索,因此需要 global 关键字.在这种情况下,您没有分配名称,因此没有必要.

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.

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

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