繁体   English   中英

python模块__init__函数

[英]python module __init__ function

有没有办法为模块(而不是包)制作隐式初始化器? 就像是:

#file: mymodule.py
def __init__(val):
    global value
    value = 5

当你导入它时:

#file: mainmodule.py
import mymodule(5)

import语句使用builtin __import__函数
因此,不可能有一个模块__init__功能。

你必须自己打电话:

import mymodule
mymodule.__init__(5)

这些东西通常没有作为重复项关闭,因此这是一个非常好的解决方案来自导入变量 TL; DR:使用配置模块,在导入模块之前配置它。

[...]对项目中的多个配置项非常有用的一种更简洁的方法是创建一个单独的配置模块,首先由包装代码导入,并在功能模块导入之前在运行时设置项目它。 此模式通常用于其他项目。

myconfig / __ init__.py:

 PATH_TO_R_SOURCE = '/default/R/source/path' OTHER_CONFIG_ITEM = 'DEFAULT' PI = 3.14 

mymodule / __ init__.py:

 import myconfig PATH_TO_R_SOURCE = myconfig.PATH_TO_R_SOURCE robjects.r.source(PATH_TO_R_SOURCE, chdir = True) ## this takes time class SomeClass: def __init__(self, aCurve): self._curve = aCurve if myconfig.VERSION is not None: version = myconfig.VERSION else: version = "UNDEFINED" two_pi = myconfig.PI * 2 

您可以在运行时从包装器更改模块的行为:

run.py:

 import myconfig myconfig.PATH_TO_R_SOURCE = 'actual/path/to/R/source' myconfig.PI = 3.14159 # we can even add a new configuration item that isn't present in the original myconfig: myconfig.VERSION="1.0" import mymodule print "Mymodule.two_pi = %r" % mymodule.two_pi print "Mymodule.version is %s" % mymodule.version 

输出:

 > Mymodule.two_pi = 6.28318 > Mymodule.version is 1.0 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM