如何在 Python 中获取当前模块中所有类的列表? [英] How can I get a list of all classes within current module in Python?
本文介绍了如何在 Python 中获取当前模块中所有类的列表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我见过很多人从一个模块中提取所有类的例子,通常是这样的:
I've seen plenty of examples of people extracting all of the classes from a module, usually something like:
# foo.py
class Foo:
pass
# test.py
import inspect
import foo
for name, obj in inspect.getmembers(foo):
if inspect.isclass(obj):
print obj
棒极了.
但我不知道如何从 current 模块中获取所有类.
But I can't find out how to get all of the classes from the current module.
# foo.py
import inspect
class Foo:
pass
def print_classes():
for name, obj in inspect.getmembers(???): # what do I do here?
if inspect.isclass(obj):
print obj
# test.py
import foo
foo.print_classes()
这可能是很明显的事情,但我什么也没找到.谁能帮帮我?
This is probably something really obvious, but I haven't been able to find anything. Can anyone help me out?
推荐答案
试试这个:
import sys
current_module = sys.modules[__name__]
在您的上下文中:
import sys, inspect
def print_classes():
for name, obj in inspect.getmembers(sys.modules[__name__]):
if inspect.isclass(obj):
print(obj)
甚至更好:
clsmembers = inspect.getmembers(sys.modules[__name__], inspect.isclass)
因为 inspect.getmembers()
需要一个谓词.
Because inspect.getmembers()
takes a predicate.
这篇关于如何在 Python 中获取当前模块中所有类的列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文