如何实现枚举嵌套类的函数?
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}
解决方法:
您可以使用下一个代码:
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]
并打印enumerate_nested_classes(A)打印[< class'__main __.B'>,< class'__main __.C'>]
NB. dir(_class)结果列表按字母顺序排序,因此当使用assert enumerate_nested_classes(A)== [A.B,A.C]时,最好使用:assert sorted(enumerate_nested_classes(A))== sorted([A.B,A.C]).