简体   繁体   English

如何在python中枚举嵌套类?

[英]How to enumerate nested classes in python?

How to implement function, which enumerate nested classes? 如何实现枚举嵌套类的函数?

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() should help here: inspect.getmembers()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']

Note that not name.startswith("__") check is needed to exclude __class__ - I suspect there is a simpler and a more pythonic way to do so, would appreciate if somebody would point that out. 请注意, not name.startswith("__")检查来排除__class__ - 我怀疑有一种更简单,更pythonic的方法,如果有人会指出这一点,我将不胜感激。

You can use the next code: 您可以使用下一个代码:

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]

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

NB. NB。 dir(_class) resulting list is sorted alphabetically, so when using assert enumerate_nested_classes(A) == [AB, AC] it is better to use: assert sorted(enumerate_nested_classes(A)) == sorted([AB, AC]) . dir(_class)结果列表按字母顺序排序,因此当使用assert enumerate_nested_classes(A) == [AB, AC] ,最好使用: assert sorted(enumerate_nested_classes(A)) == sorted([AB, AC])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM