python-如何获取内部类的列表? [英] python - how to get a list of inner classes?
问题描述
我正在编写一个包含一些嵌套类的小型Python应用程序,如下例所示:
I'm writing a small Python application that contains a few nested classes, like the example below:
class SuperBar(object):
pass
class Foo(object):
NAME = 'this is foo'
class Bar(SuperBar):
MSG = 'this is how Bar handle stuff'
class AnotherBar(SuperBar):
MSG = 'this is how Another Bar handle stuff'
我正在使用嵌套类创建某种层次结构,并提供一种实现解析器功能的干净方法.
I'm using nested classes to create some sort of hierarchy and to provide a clean way to implement features for a parser.
在某个时候,我想创建一个内部类的列表.我想要以下输出:
At some point, I want to create a list of the inner classes. I'd like to have the following output:
[<class '__main__.Bar'>, <class '__main__.AnotherBar'>]
问题是:以pythonic方式获取内部类列表的推荐方法是什么?
推荐答案
我设法通过以下方法获取内部类对象的列表:
I managed to get a list of inner class objects with the method below:
import inspect
def inner_classes_list(cls):
return [cls_attribute for cls_attribute in cls.__dict__.values()
if inspect.isclass(cls_attribute)
and issubclass(cls_attribute, SuperBar)]
它有效,但是我不确定直接使用__dict__
是否是一件好事.我之所以使用它,是因为它包含了我需要的实际class
实例,并且似乎可以跨Python 2和3移植.
It works, but I'm not sure if using __dict__
directly is a good thing to do. I'm using it because it contains the actual class
instances that I need and seems to be portable across Python 2 and 3.
这篇关于python-如何获取内部类的列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!