简体   繁体   English

包装函数的Python模块

[英]Python modules for wrapper functions

I am trying to write a generic module that provides functions that act as a wrapper to specific implementation. 我正在尝试编写一个通用模块,该模块提供充当特定实现的包装器的功能。 Example, my main.py script will call profile.py functions profile() . 例如,我的main.py脚本将调用profile.py函数profile() The profile.py will then call either machineA or machineB measure() function depending on the cmd line arg which i pass in. 然后profile.py将根据我传入的cmd行arg调用machineA或machineB measure()函数。

/main.py

    tools/profile.py  -- # provides function profile

          machineA/measure.py  # provides function measure

          machineB/measure.py # provides function measure

Currently my tools/profile.py does this 目前,我的tools / profile.py正在执行此操作

if machine == 'machineA':
  from machineA import measure
else:
  from machineB import measure

def profile():
  return measure.measure()

I am using modules to do this functionality, I think there maybe a way to do this with classes, however i am not too familiar with classes to know how to get started. 我正在使用模块来实现此功能,我认为也许可以通过类来实现此功能,但是我对类不太了解,因此不知道如何入门。 Any tips would be appreciated. 任何提示将不胜感激。

The simple (though hacky) way is to use __import__ directly. 一种简单(尽管很hacky)的方法是直接使用__import__

measure = __import__(machine).measure

Slightly cleaner would be to use the importlib module. 稍微干净一点的是使用importlib模块。

import importlib
measure = importlib.import_module(machine).measure

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

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