[英]Python 2.7: Dynamic module import in an imported module based on given variable
There are given two versions of a storage. 有两种版本的存储。 Based on the version, I need to select the proper interface module to get the result.
根据版本,我需要选择适当的接口模块以获取结果。
The file structure looks like this: 文件结构如下所示:
lib/
__init__.py
provider.py
connection.py
device.py
storage/
__init__.py
interface_v1.py # interface for storage of version 1
interface_v2.py # interface for storage of version 2
main.py
The main.py
imports provider.py
, that should import one of the interfaces listed in the storage
subpackage depending on the version of the storage. main.py
import provider.py
,应根据storage
版本导入storage
子包中列出的接口之一。
main.py: main.py:
from lib.provider import Provider
from lib.connection import Connection
from lib.device import Device
connection = Connection.establish(Device)
storage_version = Device.get_storage_version()
massage = Provider.get_data(connection)
provider.py should import an interface to the storage based on storage_version
and implement provide some functions: provider.py应该基于
storage_version
导入存储接口,并实现提供以下功能:
from storage import interface
class Provider(object):
def __init_(self):
self.storage = interface.Storage
def get_data(self, connection):
return self.storage.get_data()
def clear_storage(self, connection):
self.storage.clear_storage()
This example is not complete, but should be sufficient for the problem explanation. 这个例子并不完整,但是对于问题的解释应该足够了。
Additional question: 附加问题:
storage.__init__
to use import just the subpackage? storage.__init__
来仅导入子包? Assuming the interface_v1
and interface_v2
bith impleement a class StorageClass
I guess something like this: 假设
interface_v1
和interface_v2
实现了一个类StorageClass
我猜是这样的:
import storage.interface_v1
import storage.interface_v2
class Provider(object):
def __init__(self , version):
if version == 1:
self.storage = storage.interface_v1.StorageClass
else:
self.storage = storage.interface_v2.StorageClass
Would be the best solution - but https://docs.python.org/2/library/functions.html# import should provide a way to import a module based on name. 最好的解决方案-但是https://docs.python.org/2/library/functions.html# import应该提供一种基于名称导入模块的方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.