471,578 Members | 1,262 Online
Bytes | Software Development & Data Engineering Community
Post +

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 471,578 software developers and data experts.

Problem with __str__ if baseclass is list

#! /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)".
"""
Nov 22 '05 #1
1 1392
Edward C. Jones wrote:
#! /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)"?
Because it's coded like this:
def __str__(self):
return repr(self)

That implies str(x) == repr(x), since you don't want that, don't call
list.__str__

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


That's right. You *cannot* call list.__str__ because it contradicts
design of class A

Nov 22 '05 #2

This discussion thread is closed

Replies have been disabled for this discussion.

Similar topics

15 posts views Thread by Jim Newton | last post: by
7 posts views Thread by M O J O | last post: by
9 posts views Thread by MSDNAndi | last post: by
3 posts views Thread by Jonas Huckestein | last post: by
3 posts views Thread by Juha Nieminen | last post: by
5 posts views Thread by Konstantinos Pachopoulos | last post: by
reply views Thread by XIAOLAOHU | last post: by
reply views Thread by leo001 | last post: by
reply views Thread by Vinnie | last post: by
reply views Thread by lumer26 | last post: by

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.