将所有模块导入一个文件夹,并按其属性之一使用它们(Import all modules in one folder and use them by one of its attributes)
我正在尝试构建一个可模糊的应用程序,所以我需要一个允许我在不修改主应用程序的情况下创建新模块的方法。 为此,我正在准备允许我从文件夹导入所有模块的模块系统,并且我想通过使用类属性来选择要使用的模块。
模块:
topology_O.py :
class Topology(object): def __init__(self): self.name = 'O' self.version = 0.1 def __str__(self): string = "Topology: " + self.name string += "Version: " + str(self.version) return stringtopology_H.py :
class Topology(object): def __init__(self): self.name = 'H' self.version = 0.1 def __str__(self): string = "Topology: " + self.name string += "\n > Version: " + str(self.version) return string我想要像这样使用它们:
myTopology = some_topology_thing('O') print myTopology # Topology: O # > Version: 0.1 myTopology = some_topology_thing('H') print myTopology # Topology: H # > Version: 0.1所以这些模块将被选中并按name 。
I'm trying to build a modulable application, so I need a method that allows me to create new modules without modifying the main app. To do this I'm preparing module system that allows me to import all the module from a folder, and I want to select the module to use, by using a class attribute, for example.
The modules:
topology_O.py:
class Topology(object): def __init__(self): self.name = 'O' self.version = 0.1 def __str__(self): string = "Topology: " + self.name string += "Version: " + str(self.version) return stringtopology_H.py:
class Topology(object): def __init__(self): self.name = 'H' self.version = 0.1 def __str__(self): string = "Topology: " + self.name string += "\n > Version: " + str(self.version) return stringI would like to use them like this:
myTopology = some_topology_thing('O') print myTopology # Topology: O # > Version: 0.1 myTopology = some_topology_thing('H') print myTopology # Topology: H # > Version: 0.1So the modules will be selected and used by name.
最满意答案
importlib可以在这里提供帮助:
import importlib def some_topology_thing(topo_type): mod = importlib.import_module('topology_{}'.format(topo_type)) return mod.Topology()importlib can help here:
import importlib def some_topology_thing(topo_type): mod = importlib.import_module('topology_{}'.format(topo_type)) return mod.Topology()更多推荐
发布评论