[英]python global variable inside a module
a.py contains: a.py 包含:
ip=raw_input()
import b
show()
b.py contains: b.py 包含:
def show:
global ip
print ip
it's showing an error saying that ip is not defined.它显示一个错误,说 ip 未定义。 how can i use a variable from the main script inside a module?
如何在模块内使用主脚本中的变量?
A global declaration prevents a local variable being created by an assignment .全局声明防止通过赋值创建局部变量。 It doesn't magically search for a variable.
它不会神奇地搜索变量。
Unless you import a variable from one module to another, it is not available in other modules.除非您将变量从一个模块导入到另一个模块,否则它在其他模块中不可用。
For b
to be able to access members of a
, you would need to import a
.要使
b
能够访问a
成员,您需要导入a
。 You can't, because a
imports b
.你不能,因为
a
进口b
。
The solution here is probably just not to use global variables at all.这里的解决方案可能只是根本不使用全局变量。
The way your code is structured, it implies to me that you're treating import
as if it were effectively copying-and-pasting the contents of b.py
into a.py
.您的代码的结构方式对我来说意味着您将
import
视为有效地将b.py
的内容复制并粘贴到a.py
中。 However, that's not how Python works -- variables and functions inside one module will not be accessible in another unless explicitly passed in via a function, or by using the module.member
notation.然而,这不是 Python 的工作方式——一个模块中的变量和函数将无法在另一个模块中访问,除非通过 function 或使用
module.member
表示法显式传入。
Try doing this instead:尝试这样做:
a.py:一个.py:
import b
ip = raw_input()
b.show(ip)
b.py: b.py:
def show(ip):
print ip
If you need to do some processing within the b
module, pass in the relevant functions, make any changes, and return them.如果需要在
b
模块内做一些处理,传入相关函数,进行任何更改,然后返回。 Then, reassign them within the calling module.然后,在调用模块中重新分配它们。
Edit: if you must use globals, change b.py to look like this:编辑:如果您必须使用全局变量,请将 b.py 更改为如下所示:
ip = None
def show(temp):
global ip
ip = temp
# code here
print ip
...but it would be more ideal to restructure so that you don't end up using globals. ...但是重组会更理想,这样您就不会最终使用全局变量。
i moved some of the code of a.py
to b.py
like raw_input()
and then the b.py
just returns what is being needed in a.py
.我将
a.py
的一些代码移动到b.py
,例如raw_input()
,然后b.py
只返回a.py
中需要的内容。
so no need to worry about global variables etc. as half of the work is being done by b.py
.所以不必担心全局变量等,因为一半的工作是由
b.py
完成的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.