python递归函数中的 for循环



我尝试在递归函数中使用for循环来查找子类与其父类相关的所有路径。

class A:
pass
class B(A):
pass
class C(A):
pass
class F(A):
pass
class L(C,B):
pass
class D(B,F):
pass
class M(L,D):
pass

def bases(cls):
if cls == object:
return [object]

for Class in cls.__bases__:
return [cls] + bases(Class)

print(bases(M))
# the output should be this:
# [[M, L, C, A], [M, L, B, A], [M, D, B, A], [M, D, F, A]]

,但输出为[M, L, C, A]。关键字返回不允许For循环做得很好。然后我写了这样的代码:

for Class in cls.__bases__:
path = [cls] + bases(Class)
return path

,输出为[M, D, F, A]。我用yield代替return,但它不起作用,我得到错误:

TypeError: can only concatenate list (not "generator") to list
我能做些什么来解决这个问题?

尝试使用以下递归实现:

class A:
pass
class B(A):
pass
class C(A):
pass
class F(A):
pass
class L(C,B):
pass
class D(B,F):
pass
class M(L,D):
pass
def bases(cls):
if cls.__bases__ == (object, ): # if "root"
return [cls.__name__]
return [[cls.__name__, *granpas] for base in cls.__bases__ for granpas in bases(base)]
print(bases(M)) # [['M', 'L', 'C', 'A'], ['M', 'L', 'B', 'A'], ['M', 'D', 'B', 'A'], ['M', 'D', 'F', 'A']]

相关内容

  • 没有找到相关文章

最新更新