Python 递归类包含与实例化

0 投票
1 回答
1304 浏览
提问于 2025-04-15 12:11

我想要从一个叫做

some-dir/

的文件夹里导入一些类,这些类的文件名是class*.py。

最后,我还想创建这些类的实例。

有什么好的方法可以查看这个文件夹,导入这些类并创建实例呢?

1 个回答

0

试试这个:

import os
#get files
files = os.listdir("some-dir/")
classes = []
for f in files:
   #find python modules in file listing
   if(f.find(".py") != -1):
      #remove file extenstion
      f = f.rstrip(".py")
      #create string to add module to global namespace, import it and instantiate
      #class
      importStr = "global " + f +";import " + f + "; classes.append(" + f +"())"
      #execute the code
      exec(importStr) 

这是一个初步的尝试。这个假设你在创建这个类的时候不需要传入任何参数。

不知道这个是否有效,但这是一个开始的地方。这个“exec”语句可以让你把字符串当作Python代码来执行。

希望这能帮你找到正确的方向。

撰写回答