0

这是我递归获取所有子类的类方法:

@classmethod
def get_subclasses(cls):
    subclasses = set()
    for subclass in cls.__subclasses__():
        subclasses.add(subclass)
        subclasses.update(subclass.get_subclasses())
    return subclasses

有没有办法让它成为单线?就像是:

return set(subclass.__subclasses__() for subclass in self.__subclasses__())
4

3 回答 3

2

单行是可能的,但我认为将其保留为两行可以保持清晰度:

subclasses = set(cls.__subclasses__())
return subclasses + set(sc.get_subclasses() for sc in subclasses)
于 2015-05-04T18:00:40.050 回答
0

为了提高可读性,这是一个逻辑行分为两行源代码:

@classmethod
def get_subclasses(cls):
    return set(cls.__subclasses__()) | {g for s in cls.__subclasses__()
                                            for g in s.get_subclasses()}
于 2015-05-04T18:36:27.577 回答
-1

这将返回从基类继承的所有子类的名称。

print([cls.__name__ for cls in vars()['Base'].__subclasses__()])
于 2015-05-04T17:49:04.187 回答