python globals:导入vs. execfile [英] python globals: import vs. execfile

查看:80
本文介绍了python globals:导入vs. execfile的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在mymodule.py文件中放置了一个方法:

I put a method in a file mymodule.py:

def do_something():
    global a
    a=1

如果我尝试

>>> execfile('mymodule.py')
>>> do_something()
>>> print a

我得到的是"1".但是,如果我改为导入模块,

I get "1" as I expect. But if I import the module instead,

>>> from mymodule import *

然后运行do_something(),然后python会话对变量"a"一无所知.

and then run do_something(), then the python session knows nothing about the variable "a".

有人可以向我解释差异吗?谢谢.

Can anyone explain the difference to me? Thanks.

推荐答案

在导入mymodule的第二部分中,未显示的原因是a对于就是这样.

In the second part where you import mymodule, the reason why it isn't showing up is that a is global to the namespace of mymodule as done that way.

尝试:

print mymodule.a

此打印:

1

符合预期.

根据 Python文档:

全局语句是一个声明,它适用于整个 当前代码块.这意味着列出的标识符是 解释为全局变量.不可能分配给全球 没有全局变量的变量,尽管自由变量可能引用全局变量 没有被宣布为全球.

The global statement is a declaration which holds for the entire current code block. It means that the listed identifiers are to be interpreted as globals. It would be impossible to assign to a global variable without global, although free variables may refer to globals without being declared global.

全局语句中列出的名称不得在同一代码中使用 在该全局语句之前在文字上进行屏蔽.

Names listed in a global statement must not be used in the same code block textually preceding that global statement.

全局语句中列出的名称不得定义为正式名称 参数或for循环控制目标,类定义,函数 定义或导入语句.

Names listed in a global statement must not be defined as formal parameters or in a for loop control target, class definition, function definition, or import statement.

这篇关于python globals:导入vs. execfile的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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