什么是模块变量与全局变量? [英] What is a module variable vs. a global variable?

查看:475
本文介绍了什么是模块变量与全局变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

来自评论:"Python中的 global 基本上意味着在模块级别" .但是,在名为my_module.py:

From a comment: "global in Python basically means at the module-level". However running this code in a file named my_module.py:

import my_module as m

foo = 1
m.bar = m.foo + 1

if __name__ == "__main__":
    print('foo:', foo)
    print('m.foo:', m.foo)
    print('m.bar:', m.bar, '\n')

    for attrib in ('foo', 'bar'):
        print("'{0}' in m.__dict__: {1}, '{0}' in globals(): {2}".format(
            attrib,
            attrib in m.__dict__,
            attrib in globals()))

输出:

foo: 1
m.foo: 1
m.bar: 2 

'foo' in m.__dict__: True, 'foo' in globals(): True
'bar' in m.__dict__: True, 'bar' in globals(): False

模块和全局名称空间到底是什么?

What exactly are the module and global namespaces?

为什么在模块名称空间中有一个__dict__属性,但在全局名称空间中却没有?

Why is there a __dict__ attribute in module namespace but not in global namespace?

为什么m.bar__dict__的一部分而不是globals()的一部分?

Why is m.bar part of __dict__ and not part of globals()?

推荐答案

Python中基本上有3种不同的种类范围:

There are basically 3 different kinds of scope in Python:

  • 模块作用域(将属性保存在模块__dict__中)
  • 类/实例范围(在类或实例__dict__中保存属性)
  • 功能范围
  • module scope (saves attributes in the modules __dict__)
  • class/instance scope (saves attributes in the class or instance __dict__)
  • function scope

(也许我在那里忘了一些东西...)

(maybe I forgot something there ...)

这些工作几乎相同,除了类作用域可以动态使用__getattr____getattribute__来模拟实际上不存在的变量的存在.函数是不同的,因为您可以将变量传递给(使它们成为其作用域的一部分)并从函数中返回它们.

These work almost the same, except that class scopes can dynamically use __getattr__ or __getattribute__ to simulate the presence of a variable that does not in fact exist. And functions are different because you can pass variables to (making them part of their scope) and return them from functions.

但是,当您谈论全局(和本地范围)时,必须从可见性角度考虑它.没有总的全局作用域(除了可能是诸如intzip等的Python内置),只有全局模块作用域.这代表了您可以在模块中访问的所有内容.

However when you're talking about global (and local scope) you have to think of it in terms of visibility. There is no total global scope (except maybe for Pythons built-ins like int, zip, etc.) there is just a global module scope. That represents everything you can access in your module.

因此,在文件的开头,此大致"表示模块作用域:

So at the beginning of your file this "roughly" represents the module scopes:

然后,您import my_module as m表示m现在是对my_module的引用,并且此引用位于当前文件的全局范围内.这意味着'm' in globals()将为True.

Then you import my_module as m that means that m now is a reference to my_module and this reference is in the global scope of your current file. That means 'm' in globals() will be True.

您还定义了foo=1,它使foo成为全局范围的一部分,而'foo' in globals()将是True.但是,此foo是与m.foo完全不同的实体!

You also define foo=1 that makes foo part of your global scope and 'foo' in globals() will be True. However this foo is a total different entity from m.foo!

然后,您执行m.bar = m.foo + 1,访问全局变量m,并根据m的属性foo更改其属性bar.这并不使mfoobar成为当前全局范围的一部分.它们仍然在my_module的全局范围内,但是您可以通过全局变量m访问my_module的全局范围.

Then you do m.bar = m.foo + 1 that access the global variable m and changes its attribute bar based on ms attribute foo. That doesn't make ms foo and bar part of the current global scope. They are still in the global scope of my_module but you can access my_modules global scope through your global variable m.

我在这里用AB缩写了模块名称,但我希望它仍然可以理解.

I abbreviated the module names here with A and B but I hope it's still understandable.

这篇关于什么是模块变量与全局变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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