如果文件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))
答案 0 :(得分:2)
这有点冗长,但是您首先需要将文件作为模块加载,然后检查其方法以查看哪些是类:
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))]
答案 1 :(得分:2)
您可以同时获得:
for name, cls in inspect.getmembers(importlib.import_module("myfile"), inspect.isclass):
您可能还需要检查:
if cls.__module__ == 'myfile'
答案 2 :(得分:0)
以防万一。这是我使用的最终解决方案。此方法返回在特定程序包中定义的所有类。
我将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