Python 2.7:基于给定变量导入模块中的动态模块导入

时间:2016-04-21 20:00:16

标签: python python-2.7 python-import python-module

有两个版本的存储空间。根据版本,我需要选择合适的接口模块来获得结果。

文件结构如下所示:

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

main.py导入provider.py,应导入storage子包中列出的某个接口,具体取决于存储的版本。

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应该基于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()

此示例不完整,但应足以解决问题。

其他问题:

  • 是否可以使用storage.__init__仅使用导入 子包?
  • 如何在Python中正确实现Factory?

1 个答案:

答案 0 :(得分:0)

假设interface_v1interface_v2 bith实现了一个类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

这将是最佳解决方案 - 但https://docs.python.org/2/library/functions.html#import应该提供一种基于名称导入模块的方法。

相关问题