__str__ difficulty with lists

Jabba Laci jabba.laci at gmail.com
Sun Nov 1 16:02:25 EST 2009


Hi,

I have a list that contains custom objects. When printing the list,
I'd like to have a readable result, i.e. I'd like to see the output of
the __str__ functions. See an example below. When I call "print li", I
would like to get "[3, 5]". How to do that?

Thanks,

Laszlo

==========

class MyNumber:
    def __init__(self, n):
        self.n = n

    def __str__(self):
        return str(self.n)

if __name__ == "__main__":
    li = []
    a = MyNumber(3)
    li.append(a)
    li.append(MyNumber(5))
    print li   # [<__main__.MyNumber instance at 0xb77a456c>,
<__main__.MyNumber instance at 0xb77a46ec>]
    print a   # 3



More information about the Python-list mailing list