导入时传递变量 [英] Pass Variable On Import

查看:105
本文介绍了导入时传递变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设您在首次导入模块/类时需要花费一些时间。此功能取决于传入的变量。只需在加载模块/类时完成。然后,该类的所有实例都可以使用结果。

Let's say you have some time-consuming work to do when a module/class is first imported. This functionality is dependent on a passed in variable. It only needs to be done when the module/class is loaded. All instances of the class can then use the result.

例如,我正在使用rpy2:

For instance, I'm using rpy2:

import rpy2.robjects as robjects

PATH_TO_R_SOURCE = ## I need to pass this
robjects.r.source(PATH_TO_R_SOURCE, chdir = True) ## this takes time

class SomeClass:
  def __init__(self, aCurve):
    self._curve = aCurve

  def processCurve(self):
    robjects.r['someRFunc'](robjects.FloatVector(self._curve))

我是不是创建了一个模块级功能,我打电话来做这项工作?

Am I stuck creating a module level function that I call to do the work?

import someClass
someClass.sourceRStuff(PATH_TO_R_SOURCE)
x = someClass.SomeClass([1,2,3,4])
etc...


推荐答案

拥有模块初始化功能并非闻所未闻。 Pygame为sdl初始化函数做了这件事。所以是的,你最好的选择可能是

Having a module init function isn't unheard of. Pygame does it for the sdl initialization functions. So yes, your best bet is probably

import someModule
someModule.init(NECESSARY_DATA)
x = someModule.someClass(range(1, 5))

这篇关于导入时传递变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆