Problem with __str__ if baseclass is list

Edward C. Jones edcjones at comcast.net
Sat Nov 12 15:14:06 EST 2005


#! /usr/bin/env python

class A(list):
     def __init__(self, alist, n):
         list.__init__(self, alist)
         self.n = n

     def __str__(self):
         return 'AS(%s, %i)' % (list.__str__(self), self.n)

     def __repr__(self):
         return 'AR(%s, %i)' % (list.__repr__(self), self.n)

a = A(['x', 'y'], 7)

print 1, a
print 2, repr(a)
print 3, list.__str__(a)
print 4, list.__repr__(a)

"""
The output is:

1 AS(AR(['x', 'y'], 7), 7)
2 AR(['x', 'y'], 7)
3 AR(['x', 'y'], 7)
4 ['x', 'y']

Why is list.__str__(a) == "AR(['x', 'y'], 7)"?

Note: The problem goes away if "list.__str__(a)" is replaced with
"list.__repr__(self)".
"""



More information about the Python-list mailing list