为简化问题,假设我有4个文件。现在,我按如下所示安排它们
main.py (我在其中启动程序)
global important_arg
important_arg = sys.argv[1]
if __name__ == "__main__":
import worker_a
import worker_b
if important_arg == "0":
worker = worker_a.worker()
worker.run()
elif important_arg == "1":
worker = worker_b.worker()
worker.run()
worker_a / worker_b.py
import main
import helper
class worker:
def run(self):
a = helper.dosth()
b = helper.dosth_2()
....blah blah blah
helper.py (其中worker_a和b都需要静态功能)
import main
important_arg = main.important_arg #This is not work I know, the problem is how to make this work.
def dosth():
...
#I have tiny part need important_arg
if important_arg == "0":
print "This is worker A."
elif important_arg == "1":
print "This is worker B."
...
def dosth_2():
...
可以肯定的是,在这种模式下,我的helper.py无法再从main.py中检索important_arg
。
如果我强迫它运行,就不会感到惊讶了,
错误将会
“模块”对象没有属性“ important_arg”
我应该如何重新设计模式,或者将其从main.py传递给helper.py?
此外,我的最后一种方法是将整个helper.py转换为“类”。但这很乏味,因为我需要添加大量的“自我”。除非我发现不可能传递变量,否则现在不太可能使用此方法。