在我的问题中,我有一个由用户启动的python代码,如:
# file main.py
import sys
import mymodule
config = sys.argv[1]
其中导入另一个包含函数,类等的模块
# module.py
def check_config():
# do something with the content of 'config'
class Module(object):
# does something with the content of 'config'
如何从module.py中访问’config’的值?我应该在这里使用’全球’变量吗?或者是否有更复杂的pythonic方法来解决这个问题?
另外,我不想为我在其他模块中使用的每个函数和类定义一个参数’config’…
进一步说明:main.py导入其他模块,而不是相反…
解决方法:
您应该将config作为参数传递,而不是试图将全局变为执行此操作.
文件main.py
import sys
import mymodule
config = sys.argv[1]
checked = mymodule.check_config(config)
mod = mymodule.Module(config)
module.py
def check_config(config):
# do something with the content of 'config'
class Module(object):
# does something with the content of 'config'
def __init__(self, config):
# initialise with config
尽可能避免使用全局.如果你需要修改配置只需要一个模块函数返回它.
config = change_config(config)
module.py
def change_config(config):
...
return config
但是,另一种方法是在module.py中定义一个值,该值将存储默认情况下不保留任何内容的信息.然后,只要文件main.py导入了module.py并且配置数据就绪,您就可以将数据分配给module.py的配置名称.像这样:
文件main.py
import sys
import mymodule
config = sys.argv[1]
mymodule.config = config
mymodule.test_config()
mymodule.check_config()
mymodule.Module()
module.py
config = None
def test_config():
print config
# this will refer to the value supplied from file main.py
但请注意,模块和主文件中的值不会连接.如果由于任何原因重新分配文件main.py中的config,则必须再次将该值传递给模块.但是,如果您传递一个像dict或list这样的可变值,那么您可以在main.py文件中修改它,并且将共享这些值.
标签:python,global-variables