ayirtrebor
ayirtrebor

Reputation: 53

Problems with `__str__` method in recursive list type objects

I'm trying to make an object which basically a list, but with extra features. when i use it (such as by printing it) I want a custom display. for example:

class MyList(list):
    def __init__(self, name, arg):
        self.name=name
        super().__init__(arg)
    def __str__(self):
        return "{0}: {1}".format(self.name,self[:])
if __name__=="__main__":
    B = MyList("george",range(3))
    A = MyList("bernadett",range(5,0,-1))
    B.append(A)
    A.append(B)
    print(B)

It prints out george: [0, 1, 2, [5, 4, 3, 2, 1, [0, 1, 2, [...]]]] I would like it to always print the name of the Mylist before going into the list, and I would rather limit the recursion depth to 1, instead it should just print the name and leave it at that.

so I would like something like: George: [0, 1, 2, Bernadette: [5, 4, 3, 2, 1, George:]]

also, whenever I try to alter the __repr__ for the list type object, I get infinite loops and I don't know why.

thanks.

Upvotes: 2

Views: 889

Answers (1)

JBernardo
JBernardo

Reputation: 33397

Use the parent representation:

def __repr__(self):
    return "{0}: {1}".format(self.name, super().__repr__())

You have to define this as the __repr__ method, because on lists it is the one used to print the elements inside it.

Doing that, the above code will result in:

george: [0, 1, 2, bernadett: [5, 4, 3, 2, 1, george: [...]]]

Upvotes: 2

Related Questions