[英]Python: Handover a variable while calling a module
在 python 中,我想调用一个自建模块并将其交给某个变量(例如 integer 编号)。 通过这个,我想指定从哪个文件调用模块,即当我从文件 A 导入模块 XY 时,模块将在某种模式下工作(由变量指定),如果我从文件导入模块 XY B、模块工作在其他模式
我的第一个想法是通过定义函数来做到这一点; 但是当我的模块中有很多功能时,我必须在每个 function 中单独添加这个额外的变量。
导入模块时是否有更优雅的方法来为模块分配某个变量/操作模式?
import mymodule # here, I'd like to hand-over a global variable to "mymodule" which can be used in the source-code of "mymodule"
mymodule.any_function_from_it()
模块“mymodule”可能具有以下结构:
def any_function_from_it_independent_from_global_variable():
print("x")
# more code to follow here
if variable_handed_over==0:
def any_function_from_it():
print("xy")
# more code to follow here
else:
def any_function_from_it():
print("xyz")
# more code to follow here
有几十种不同的方法可以实现您似乎想要的一般最终结果 - 但“在导入时根据“传递的变量”的值配置模块以不同的行为”不是其中之一。
这是一个模块,显示了两种常见的方法来做你所描述的事情。 第一种方法,使用 class ThingDoer
是一种面向对象的方法。 第二种方法,使用 function get_thing_doer
是一种功能方法。
模块: doers.py
class ThingDoer(object):
def __init__(self, is_special_mode=False):
self._is_special_mode = is_special_mode
def _special_mode_do_it(self):
print("I'm special!")
def _do_it(self):
print("I'm not special, but please accept me anyway")
def do_the_thing(self):
if self._is_special_mode:
self._special_mode_do_it()
return
self._do_it()
def get_thing_doer(is_special_mode=False):
def special_mode_do_it():
print("I'm special")
def do_it():
print("I'm not special, but please accept me anyway")
if is_special_mode:
return special_mode_do_it
return do_it
您可以通过在同一目录中创建另一个模块来了解其工作原理。
模块: do_it.py
from doers import get_thing_doer, ThingDoer
if __name__ == '__main__':
foo = ThingDoer() # is_special_mode argument takes default value of False
foo.do_the_thing() # prints: "I'm not special, but please love me anyway!"
bar = ThingDoer(is_special_mode=True)
bar.do_the_thing() # prints: "I'm Special!"
bazz = get_thing_doer() # is_special_mode argument takes default value of False
bazz() # prints: "I'm not special, but please love me anyway!"
buzz = get_thing_doer(is_special_mode=True)
buzz() # prints "I'm special!"
然后,从命令行运行: python do_it.py
。
更抽象地说:在 python 中,条件行为通常不在导入时基于状态配置进行管理。
相反,条件行为(基于配置或其他应用程序状态)作为程序执行流程的一部分发生。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.