Python - What priority does global have?

南楼画角 提交于 2019-11-29 11:52:08

How global are global variables?

So-called "global" variables in Python are really module-level. There are actually-global globals, which live in the __builtin__ module in Python 2 or builtins in Python 3, but you shouldn't touch those. (Also, note the presence or lack of an s. __builtins__ is its own weird thing.)

What does the global statement do?

The global statement means that, for just the function in which it appears, the specified variable name or names refer to the "global" (module-level) variable(s), rather than local variables.

What about import *?

Oh god, don't do that. Globals are bad enough, but importing them is worse, and doing it with import * is just about the worst way you could do it. What the import system does with global variables is horribly surprising to new programmers and almost never what you want.

When you do import *, that doesn't mean that your module starts looking in the imported module's global variables for variable lookup. It means that Python looks in the imported module, finds its "public" global variables*, and assigns their current values to identically-named new global variables in the current module.

That means that any assignments to your new global variables won't affect the originals, and any assignments to the originals won't affect your new variables. Any functions you imported with import * are still looking at the original variables, so they won't see changes you make to your copies, and you won't see changes they make to theirs. The results are a confusing mess.

Seriously, if you absolutely must use another module's global variables, import it with the import othermodule syntax and access the globals with othermodule.whatever_global.


*If the module defines an __all__ list, the "public" globals are the variables whose names appear in that list. Otherwise, they're the variables whose names don't start with an underscore. defined functions are stored in ordinary variables, so those get included under the same criteria as other variables.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!