Velocity Reviews - Computer Hardware Reviews

Velocity Reviews > Newsgroups > Programming > Python > Problem with __str__ if baseclass is list

Reply
Thread Tools

Problem with __str__ if baseclass is list

 
 
Edward C. Jones
Guest
Posts: n/a
 
      11-12-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)".
"""
 
Reply With Quote
 
 
 
 
Serge Orlov
Guest
Posts: n/a
 
      11-13-2005
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

 
Reply With Quote
 
 
 
Reply

Thread Tools

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are Off


Similar Threads
Thread Thread Starter Forum Replies Last Post
cpython list __str__ method for floats [david] Python 6 09-12-2007 11:48 PM
common baseclass for stl classes? andy C++ 2 03-17-2005 03:09 PM
overwriting method in baseclass Harald Massa Python 5 02-09-2005 09:13 PM
Accessing a protected member of a member of type BaseClass???? Steven T. Hatton C++ 2 08-16-2004 03:11 PM
classes: virtual functions from baseclass verbatime C++ 7 03-04-2004 06:53 PM



Advertisments
 



1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57