python – __str__ and list

Question:

I have a class:

class MyClass():
    def __init__(self, n):
        self.n = n
    
    def __str__(self):
        return str(self.n)

and a list arr , which contains instances of the class:

arr = [MyClass(0), MyClass(1)]

how to make it print(arr) :

['0', '1']

but not:

[<__main__.MyClass object at 0xebeb3dc0>, <__main__.MyClass object at 0xebdcb580>]

full code:

class MyClass():
    def __init__(self, n):
        self.n = n
    
    def __str__(self):
        return str(self.n)

arr = [MyClass(0), MyClass(1)]

print(arr)

Answer:

Add the implementation of the special __repr__ method:

def __repr__(self):
    return str(self.n)
Scroll to Top