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

问题描述

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

到目前为止,我的尝试:

My attempts so far:

方法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.

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

08-24 02:53