将所有模块导入一个文件夹,并按其属性之一使用它们(Import all modules in one folder and use them by one of its attributes)

编程入门 行业动态 更新时间:2024-10-25 15:35:01
将所有模块导入一个文件夹,并按其属性之一使用它们(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 string

topology_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 string

topology_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

I 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.1

So 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()

更多推荐

本文发布于:2023-08-03 07:19:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1385245.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:文件夹   按其   模块   属性   folder

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!