[Tutor] Numbers do support __str__() in recent versions of Python
Danny Yoo
dyoo at hkn.eecs.berkeley.edu
Fri Nov 21 19:41:10 EST 2003
On Fri, 21 Nov 2003, Danny Yoo wrote:
>
> > In recent years, the __str__() method was added to numbers to make them
> > more uniform with the other Python types and classes.
>
> Hi everyone,
>
>
> Yikes, I'm totally wrong here! Numbers still don't have __str__().
Hi everyone,
I'm definitely having an off day. I'm wrong again. *grin*
Ok, let's do this:
###
[dyoo at tesuque dyoo]$ python1.5
Python 1.5.2 (#1, Jan 31 2003, 10:58:35) [GCC 2.96 20000731 (Red Hat
Linux 7.3 2 on linux-i386
Copyright 1991-1995 Stichting Mathematisch Centrum, Amsterdam
>>> x = 42
>>> x.__str__()
Traceback (innermost last):
File "<stdin>", line 1, in ?
AttributeError: 'int' object has no attribute '__str__'
[dyoo at tesuque dyoo]$ python2.2
Python 2.2.1 (#1, Sep 3 2002, 14:52:01)
[GCC 2.96 20000731 (Red Hat Linux 7.3 2.96-112)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> x = 42
>>> x.__str__()
'42'
###
So numbers do have __str__() now, after all.
I need to explain why I blundered: I did not pay close enough attention to
the error message when I tested this out earlier:
###
>>> 42.__str__()
File "<stdin>", line 1
42.__str__()
^
SyntaxError: invalid syntax
###
This fails, but not because numbers don't support __str__(), but because
PYthon is parsing this out as a floating point value that isn't proper
syntax!
###
>>> 42.3
42.299999999999997
>>> 42.4
42.399999999999999
>>> 42.__str__()
File "<stdin>", line 1
42.__str__()
^
SyntaxError: invalid syntax
###
I should have payed closer attention to the error message: I mistook the
SyntaxError for an AttributeError, and that led me astray.
Anyway, if we add parentheses here, we get rid of the ambiguity, and, as I
should have said earlier:
###
>>> (42).__str__()
'42'
###
Numbers do support __str__(). Again, my apologies for giving totally off
advice. I think I need a vacation... *grin*
Good luck!
More information about the Tutor
mailing list