如果文件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))
你可以得到两个:
for name, cls in inspect.getmembers(importlib.import_module("myfile"), inspect.isclass):
你可能还想检查:
if cls.__module__ == 'myfile'
这有点啰嗦,但您首先需要将文件作为模块加载,然后检查其方法以查看哪些类:
import inspect
import importlib.util
# Load the module from file
spec = 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))]
万一它可以帮助别人。这是我使用的最终解决方案。此方法返回特定包中定义的所有类。
我将X的所有子类保存在特定的文件夹(包)中,然后,使用此方法,我可以加载X的所有子类,即使它们尚未导入。 (如果它们尚未导入,则无法通过__all__
访问它们;否则事情就会变得容易得多)。
import importlib, os, inspect
def 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