简体   繁体   English

什么是模块变量与全局变量?

[英]What is a module variable vs. a global variable?

From a comment : " global in Python basically means at the module-level". 来自评论 :“Python中的全局基本上意味着在模块级别”。 However running this code in a file named my_module.py : 但是,在名为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()))

Output: 输出:

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? 模块和全局命名空间究竟是什么?

Why is there a __dict__ attribute in module namespace but not in global namespace? 为什么模块命名空间中有__dict__属性但在全局命名空间中没有?

Why is m.bar part of __dict__ and not part of globals() ? 为什么m.bar__dict__一部分而不是globals()一部分?

There are basically 3 different kinds of scope in Python: Python中基本上有3 不同的范围:

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

(maybe I forgot something there ...) (也许我忘了那里......)

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. 这些工作几乎相同,只是类范围可以动态使用__getattr____getattribute__来模拟实际上不存在的变量的存在。 And functions are different because you can pass variables to (making them part of their scope) and return them from functions. 函数是不同的,因为您可以传递变量(使它们成为其范围的一部分)并从函数返回它们。

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 . 没有全局范围 (除了像Pythons内置插件,如intzip等),只有一个全局模块范围 That represents everything you can access in your module. 这表示您可以在模块中访问的所有内容。

So at the beginning of your file this "roughly" represents the module scopes: 因此,在文件的开头,这个“粗略”表示模块范围:

在此输入图像描述

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. 然后import my_module as m ,这意味着m now现在是对my_module的引用,并且此引用位于当前文件的全局范围内。 That means 'm' in globals() will be True. 这意味着'm' in globals()将为True。

在此输入图像描述

You also define foo=1 that makes foo part of your global scope and 'foo' in globals() will be True . 你还定义了foo=1 ,它使foo成为全局范围的一部分,而'foo' in globals()将为True However this foo is a total different entity from m.foo ! 然而,这个foo是与m.foo完全不同的实体!

在此输入图像描述

Then you do m.bar = m.foo + 1 that access the global variable m and changes its attribute bar based on m s attribute foo . 然后你做m.bar = m.foo + 1访问全局变量m并根据m s属性foo更改属性bar That doesn't make m s foo and bar part of the current global scope. 这不会让m小号foobar目前全球范围的一部分。 They are still in the global scope of my_module but you can access my_module s global scope through your global variable m . 它们仍然在my_module的全局范围内,但您可以通过全局变量m访问my_module的全局范围。

在此输入图像描述

I abbreviated the module names here with A and B but I hope it's still understandable. 我在这里用AB缩写了模块名称,但我希望它仍然可以理解。

A global variable is where you can use the variable at any given time, even in a function or a for loop. 全局变量是您可以在任何给定时间使用变量的地方,即使在函数或for循环中也是如此。 A localized variable is defined in a function, but not returned. 本地化变量在函数中定义,但不返回。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM