检查模块中的类是否实现了正确的接口

0 投票
1 回答
1594 浏览
提问于 2025-04-16 21:46

我有一个接口:

class Interface(object):

    __metaclass__ = abc.ABCMeta


    @abc.abstractmethod
    def run(self):
        """Run the process."""
        return

我有一堆模块,它们都在同一个文件夹里。每个模块里面都有一个类,这个类实现了我的接口。

比如说,Launch.py:

class Launch(Interface):

    def run(self):
        pass

假设我有20个模块,每个模块里面都有一个类。我的目标是启动一个模块,检查一下这些类有没有不实现接口的情况。

我知道我需要用到:

  • issubclass(Launch, ProcessInterface) 来判断某个类是否实现了我的进程接口。
  • 使用反射来获取模块里的类。
  • 在运行时导入模块。

不过我不太确定该怎么做。 我能在模块内部使用issubclass。 但如果我在模块外部,就不能使用issubclass了。

我需要:

  1. 获取目录下所有模块的列表
  2. 获取每个模块里的类
  3. 对每个类使用issubclass

我需要一个可以实现这些功能的函数草稿。

1 个回答

0

你可能在寻找类似这样的东西:

from os import listdir
from sys import path

modpath = "/path/to/modules"

for modname in listdir(modpath):
    if modname.endswith(".py"):

        # look only in the modpath directory when importing
        oldpath, path[:] = path[:], [modpath]

        try:
            module = __import__(modname[:-3])
        except ImportError:
            print "Couldn't import", modname
            continue
        finally:    # always restore the real path
            path[:] = oldpath

        for attr in dir(module):
            cls = getattr(module, attr)
            if isinstance(cls, type) and not issubclass(cls, ProcessInterface):
                # do whatever

撰写回答