如何实现枚举嵌套类的函数?
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}
alecxe.. 6
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']
请注意,not name.startswith("__")
需要检查以排除__class__
- 我怀疑有更简单和更pythonic的方式这样做,如果有人会指出这一点,将不胜感激.
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']
请注意,not name.startswith("__")
需要检查以排除__class__
- 我怀疑有更简单和更pythonic的方式这样做,如果有人会指出这一点,将不胜感激.