str behaviour

Jay O'Connor joconnor at cybermesa.com
Thu Mar 1 11:14:13 EST 2001


"Igor V. Rafienko" wrote:

> Hi,
>
> I was playing around with printing tuples, when I noticed how str
> behaves with "compound" types (such as tuples):
>
> >>> class A:
> ...     def __str__( self ):
> ...         return "I'm A"
> ...
> >>> a = A()
> >>> t = ( A, a )
> >>> str( t )
> '(<class __main__.A at 80fd498>, <__main__.A instance at 810f090>)'
> >>> str( a )
> "I'm A"
> >>>
>
> I expected str to be called recursively for the constituent types.
> But, alas, that did not happen. Am I misunderstanding something or is
> it the intended behaviour? If the latter is the case, could someone
> elaborate on why this behaviour was chosen?

Not looking inside the code for printing a code, experimation indicates
that __str__ is not being called, but __repr__ is...

>>> class ClassA:
    def __str__(self):
        return "I'm an A"
    def __repr__(self):
        return "I'm really an A"

>>> a = ClassA()
>>> a
I'm really an A
>>> t = (ClassA, a)
>>> t
(<class __main__.ClassA at 0096F9AC>, I'm really an A)
>>>

--
Jay O'Connor
joconnor at cybermesa.com
http://www.cybermesa.com/~joconnor

Python Language Forum -
http://pub1.ezboard.com/fobjectorienteddevelopmentpython





More information about the Python-list mailing list