如何枚举 python 中嵌套的 类?

How to enumerate nested classes in python?

如何实现枚举嵌套的函数类?

class A(object):
    class B(object):
        pass

    class C(object):
        pass


def enumerate_nested_classes(_class):
    return ()  # need proper implementation instead


assert set(enumerate_nested_classes(A)) == {A.B, A.C}

inspect.getmembers() in conjunction with inspect.isclass() 应该对这里有所帮助:

classes = [name for name, member_type in inspect.getmembers(A)
           if inspect.isclass(member_type) and not name.startswith("__")]

print(classes)  # prints ['B', 'C']

请注意,需要 not name.startswith("__") 检查才能排除 __class__ - 我怀疑有一种更简单、更 pythonic 的方法可以做到这一点,如果有人指出,我将不胜感激出.

您可以使用下一个代码:

import types


class A(object):
    class B(object):
        pass

    class C(object):
        pass

def enumerate_nested_classes(_class):
    return [getattr(_class, n) for n in dir(_class) if not n.startswith('__')
            and isinstance(getattr(_class, n), (type, types.ClassType))] 

assert enumerate_nested_classes(A) == [A.B, A.C]

并且 print enumerate_nested_classes(A) 打印 [<class '__main__.B'>, <class '__main__.C'>]

注意。 dir(_class) 结果列表按字母顺序排序,因此在使用 assert enumerate_nested_classes(A) == [A.B, A.C] 时最好使用:assert sorted(enumerate_nested_classes(A)) == sorted([A.B, A.C]).