Problem with __str__ if baseclass is list

Discussion in 'Python' started by Edward C. Jones, Nov 12, 2005.

  1. #! /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)".
    """
     
    Edward C. Jones, Nov 12, 2005
    #1
    1. Advertising

  2. Edward C. Jones

    Serge Orlov Guest

    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
     
    Serge Orlov, Nov 13, 2005
    #2
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. verbatime
    Replies:
    7
    Views:
    362
    John Harrison
    Mar 4, 2004
  2. Steven T. Hatton
    Replies:
    2
    Views:
    432
    tom_usenet
    Aug 16, 2004
  3. andy
    Replies:
    2
    Views:
    356
    Dietmar Kuehl
    Mar 17, 2005
  4. Harald Massa

    overwriting method in baseclass

    Harald Massa, Feb 7, 2005, in forum: Python
    Replies:
    5
    Views:
    343
    Harald Massa
    Feb 9, 2005
  5. [david]
    Replies:
    6
    Views:
    313
    John Machin
    Sep 13, 2007
Loading...

Share This Page