gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 07:50:47 25 4
gpt4 key购买 nike

如果文件 myfile.py 包含:

class A(object):
# Some implementation

class B (object):
# Some implementation

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

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

(即 type(A) = type(str) 或 type(A) = type(type))

最佳答案

你可以同时获得:

import importlib, inspect
for name, cls in inspect.getmembers(importlib.import_module("myfile"), inspect.isclass):

您可能还想检查:

if cls.__module__ == 'myfile'

关于python - 在 Python 中,如何获取特定文件中定义的类列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55067166/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com