[英]How to edit global variable in module?
我正在編寫一個Python模塊,並且具有一個在模塊中定義新變量的函數。 我想設置一個可以在導入文件的文件中訪問的變量。 如果這令人困惑,這是我的代碼:
# main.py
import other_module
other_module.set_variable("var1")
print(other_module.var1) # This is not a NameError
print(var1) # NameError
但是,如果我做一些稍微不同的事情:
# main.py
from other_module import *
set_variable("var1")
print(var1) # NameError
print(other_module.var1) # NameError
和other_module.py
:
# other_module.py
def set_variable(name):
exec("""
global %s
%s = 5
""" % (name, name))
我無法控制main.py
那就是消費者的密碼。 我希望能夠訪問和更改main.py
的全局變量。 我想要這個工作:
# main.py
from other_module import *
set_variable("var")
print(var) # This should print 5
對我來說,您正在做的事情聽起來像類方法行為。 一個類比全局名稱空間更安全使用,請嘗試一個類?
這有效:
# 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.