简体   繁体   中英

for loop in recursive function python

I tried to use for loop in a recursive function to find all path that the child class related to its parents.

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]]

but the output is [M, L, C, A] . keyword Return didn't allow For Loop to do well . then I wrote the code like this:

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

and the output would be [M, D, F, A] . I replaced return with yield but it didn't work and I get error:

TypeError: can only concatenate list (not "generator") to list

what can I do to solve this problem???

Try the following implementation using recursion:

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']]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM