我见过很多人从一个模块中提取所有类的例子,通常是这样的:

# foo.py
class Foo:
    pass

# test.py
import inspect
import foo

for name, obj in inspect.getmembers(foo):
    if inspect.isclass(obj):
        print obj

太棒了。

但是我不知道如何从当前模块中获得所有的类。

# 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()

这可能是非常明显的事情,但我还没有找到任何东西。有人能帮帮我吗?


当前回答

另一个适用于Python 2和3的解决方案:

#foo.py
import sys

class Foo(object):
    pass

def print_classes():
    current_module = sys.modules[__name__]
    for key in dir(current_module):
        if isinstance( getattr(current_module, key), type ):
            print(key)

# test.py
import foo
foo.print_classes()

其他回答

import Foo 
dir(Foo)

import collections
dir(collections)
import pyclbr
print(pyclbr.readmodule(__name__).keys())

注意,stdlib的Python类浏览器模块使用静态源分析,因此它只适用于由真正的.py文件支持的模块。

是什么

g = globals().copy()
for name, obj in g.iteritems():

?

另一个适用于Python 2和3的解决方案:

#foo.py
import sys

class Foo(object):
    pass

def print_classes():
    current_module = sys.modules[__name__]
    for key in dir(current_module):
        if isinstance( getattr(current_module, key), type ):
            print(key)

# test.py
import foo
foo.print_classes()

以下内容可以放在文件的顶部:

def get_classes():
    import inspect, sys
    return dict(inspect.getmembers(
        sys.modules[__name__],
        lambda member: inspect.isclass(member) and member.__module__ == __name__
    ))

注意,这可以放在模块的顶部,因为我们已经将逻辑包装在函数定义中。如果希望字典作为顶级对象存在,则需要将定义放在文件的底部,以确保包括所有类。