Skip to main content
 首页 » 编程设计

python之将工厂、 super 和子从一个模块中分离出来

2025年05月04日15shanyou

我有一个工作模块,其中包含一个工厂函数、一个父类(super class)和两个子类。实际模块是here .

我将工厂拆分到它自己的文件中,并将两个子类放入 commands/目录中,这样我就可以解决由于在包含我的 super 模块中导入我的子类而导致的递归问题。

就在我认为我已正确导入所有内容时,当我尝试时工厂卡住了一个空的子类列表:

for cls in Command.__subclasses__(): 

请您参考如下方法:

虽然不漂亮,但很管用。我想要一种更优雅的方法来将字符串转换为类名。遍历 __subclasses__ 确实太挑剔了。我只是不太了解元类,无法应用它。

from commands.shVersionCmd import shVersionCmd 
from commands.shVRFCmd import shVRFCmd 
def CommandFactory(commandnode): 
    if commandnode.attrib['name'] == 'shVersionCmd': return shVersionCmd(commandnode)         
    if commandnode.attrib['name'] == 'shVRFCmd': return shVRFCmd(commandnode)