有没有办法 "one-line" 使用 list/set 理解?
Is there a way to "one-line" this using list/set comprehension?
这是我递归获取所有子类的类方法:
@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__())
所有子class的这个returns名称继承自基class。
print([cls.__name__ for cls in vars()['Base'].__subclasses__()])
一行是可能的,但我认为保持两行可以保持清晰度:
subclasses = set(cls.__subclasses__())
return subclasses + set(sc.get_subclasses() for sc in subclasses)
为了提高可读性,这是一个逻辑行,分为两行源代码:
@classmethod
def get_subclasses(cls):
return set(cls.__subclasses__()) | {g for s in cls.__subclasses__()
for g in s.get_subclasses()}
这是我递归获取所有子类的类方法:
@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__())
所有子class的这个returns名称继承自基class。
print([cls.__name__ for cls in vars()['Base'].__subclasses__()])
一行是可能的,但我认为保持两行可以保持清晰度:
subclasses = set(cls.__subclasses__())
return subclasses + set(sc.get_subclasses() for sc in subclasses)
为了提高可读性,这是一个逻辑行,分为两行源代码:
@classmethod
def get_subclasses(cls):
return set(cls.__subclasses__()) | {g for s in cls.__subclasses__()
for g in s.get_subclasses()}