我有一个工厂函数,它定义了几个类并在列表中返回它们。是否可以获得这样的列表,其中类按照定义的顺序出现?
以下工厂用于locals()
获取在其范围内定义的类,但locals()
返回一个字典,因此没有明确的顺序。
import inspect
def factory() :
class Base(object):
pass
class A(Base):
pass
class B(Base):
pass
class C(Base):
pass
local_classes = [obj for obj in locals().values() if inspect.isclass(obj)]
return [cls for cls in local_classes if issubclass(cls, Base)]
factory()
# [<class '__main__.A'>, <class '__main__.Base'>, <class '__main__.C'>, <class '__main__.B'>]
所需的输出将是
# [<class '__main__.Base'>, <class '__main__.A'>, <class '__main__.B'>, <class '__main__.C'>]