在 Python 中,如何获取特定文件中定义的类列表?

如果文件myfile.py包含:


class A(object):

  # Some implementation


class B (object):

  # Some implementation

我如何定义一个方法,以便在给定的myfile.py情况下返回 [A, B]?


这里,A 和 B 的返回值可以是类的名称或类的类型。


(i.e. type(A) = type(str) or type(A) = type(type))


料青山看我应如是
浏览 264回答 3
3回答

慕桂英4014372

您可以同时获得:import importlib, inspect for name, cls in inspect.getmembers(importlib.import_module("myfile"), inspect.isclass):您可能还想检查:if cls.__module__ == 'myfile'

当年话下

万一它帮助别人。这是我使用的最终解决方案。此方法返回在特定包中定义的所有类。我将 X 的所有子类保存在特定文件夹(包)中,然后,使用此方法,我可以加载 X 的所有子类,即使它们尚未导入。(如果它们尚未导入,则无法通过 访问它们__all__;否则事情会容易得多)。import importlib, os, inspectdef get_modules_in_package(package_name: str):    files = os.listdir(package_name)    for file in files:        if file not in ['__init__.py', '__pycache__']:            if file[-3:] != '.py':                continue            file_name = file[:-3]            module_name = package_name + '.' + file_name            for name, cls in inspect.getmembers(importlib.import_module(module_name), inspect.isclass):                if cls.__module__ == module_name:                    yield cls

HUWWW

这有点冗长,但您首先需要将文件作为模块加载,然后检查其方法以查看哪些是类:import inspectimport importlib.util# Load the module from filespec = importlib.util.spec_from_file_location("foo", "foo.py")foo = importlib.util.module_from_spec(spec)spec.loader.exec_module(foo)# Return a list of all attributes of foo which are classes[x for x in dir(foo) if inspect.isclass(getattr(foo, x))]
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python