简体   繁体   English

python模块__init__函数

[英]python module __init__ function

Is there any way to make an implicit initializer for modules (not packages)? 有没有办法为模块(而不是包)制作隐式初始化器? Something like: 就像是:

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

And when you import it: 当你导入它时:

#file: mainmodule.py
import mymodule(5)

The import statement uses the builtin __import__ function . import语句使用builtin __import__函数
Therefore it's not possible to have a module __init__ function. 因此,不可能有一个模块__init__功能。

You'll have to call it yourself: 你必须自己打电话:

import mymodule
mymodule.__init__(5)

These things often are not closed as duplicates, so here's a really nice solution from Pass Variable On Import . 这些东西通常没有作为重复项关闭,因此这是一个非常好的解决方案来自导入变量 TL;DR: use a config module, configure that before importing your module. TL; DR:使用配置模块,在导入模块之前配置它。

[...] A cleaner way to do it which is very useful for multiple configuration items in your project is to create a separate Configuration module that is imported by your wrapping code first, and the items set at runtime, before your functional module imports it. [...]对项目中的多个配置项非常有用的一种更简洁的方法是创建一个单独的配置模块,首先由包装代码导入,并在功能模块导入之前在运行时设置项目它。 This pattern is often used in other projects. 此模式通常用于其他项目。

myconfig/__init__.py : myconfig / __ init__.py:

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

mymodule/__init__.py : 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 

And you can change the behaviour of your module at runtime from the wrapper: 您可以在运行时从包装器更改模块的行为:

run.py : 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 

Output: 输出:

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

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

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