is there a way to define a recursive __repr__ for a class that contains itself?

Viewed 96

Let's say that I have a class:

class Band():
    def __init__(self, name, members):
        self.name = name
        self.members = members

    def __repr__(self):
        return f'''{self.name} [{', '.join(self.members)}]'''

If I create two instances of it like this:

Band_A = Band('Band A', ['Tom', 'Josh'])
Band_B = Band('Band B', ['Mark', 'Steve'])

When I print them, I get the expected result:

Band A [Tom, Josh]
Band B [Mark, Steve]

But when I create an instance of the class that contains itself, then it doesn't work.

Band_C = Band('Band C', [Band_A, Band_B])

I get this error:

Traceback (most recent call last):
  File "c:/Users/IcyTear/Desktop/test.py", line 16, in <module>
    print(Band_C)
  File "c:/Users/IcyTear/Desktop/test.py", line 7, in __repr__
    return f'''{self.name} [{', '.join(self.members)}]'''
TypeError: sequence item 0: expected str instance, Band found

Is there a way to make it work so it displays this?

Band C [Band A [Tom, Josh], Band B [Mark, Steve]]
1 Answers

Change your __repr__(self) to

def __repr__(self):
    return f'''{self.name} [{', '.join(map(repr, self.members))}]'''

to get

Band C [Band A [Tom, Josh], Band B [Mark, Steve]]

str.join() want an iterable of string, so explicitly convert every member into its string representation using map(repr, ...)

Related