[英]How to edit global variable in module?
I am writing a Python module and I have a function that defines a new variable in the module. 我正在编写一个Python模块,并且具有一个在模块中定义新变量的函数。 I want to set a variable that can be accessed in the file that is importing the file.
我想设置一个可以在导入文件的文件中访问的变量。 If that is confusing, here is my code:
如果这令人困惑,这是我的代码:
# main.py
import other_module
other_module.set_variable("var1")
print(other_module.var1) # This is not a NameError
print(var1) # NameError
However, if I do something slightly different: 但是,如果我做一些稍微不同的事情:
# main.py
from other_module import *
set_variable("var1")
print(var1) # NameError
print(other_module.var1) # NameError
And other_module.py
: 和
other_module.py
:
# other_module.py
def set_variable(name):
exec("""
global %s
%s = 5
""" % (name, name))
I have no control over main.py
. 我无法控制
main.py
That is thr consumer's code. 那就是消费者的密码。 I want to be able to access and change
main.py
's globals. 我希望能够访问和更改
main.py
的全局变量。 I want this to work: 我想要这个工作:
# main.py
from other_module import *
set_variable("var")
print(var) # This should print 5
What you are doing sounds like class method behavior to me. 对我来说,您正在做的事情听起来像类方法行为。 A class will be safer to use than the global namespace, try a class?
一个类比全局名称空间更安全使用,请尝试一个类?
This works: 这有效:
# other.py
class Other(object):
@classmethod
def set_variable(cls, name):
exec('Other.%s = 5' % name)
# main.py
from other import Other
Other.set_variable('x')
print Other.x
# output
% ./main.py
5
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.