Overriding the __new__ method

Peter Otten __peter__ at web.de
Sun Feb 8 11:46:08 EST 2004


Christoph Groth wrote:

> Hello,
> 
> The essay "Unifying types and classes in Python 2.2"
> http://www.python.org/2.2.1/descrintro.html says in section
> "Overriding the __new__ method":
> 
> <quote>
> This class isn't very useful (it's not even the right way to go about
> unit conversions) but it shows how to extend the constructor of an
> immutable type. If instead of __new__ we had tried to override
> __init__, it wouldn't have worked:
> 
>     >>> class inch(float):
>     ...     "THIS DOESN'T WORK!!!"
>     ...     def __init__(self, arg=0.0):
>     ...         float.__init__(self, arg*0.0254)
>     ...
>     >>> print inch(12)
>     12.0
>     >>> 
> </quote>
> 
> Well, I tried this with Python 2.2.1 and it _does_ work:

No, it doesn't.
> 
> piglet:~$ python
> Python 2.2.1 (#1, Sep  7 2002, 14:34:30)
> [GCC 2.95.4 20011002 (Debian prerelease)] on linux2
> Type "help", "copyright", "credits" or "license" for more information.
>>>> class inch(float):
> ...     def __init__(self, arg=0.0):
> ...         float.__init__(self, arg*0.0254)
> ...
>>>> print inch(12)
> 12.0
 
So one inch is one meter?

Python 2.3.3 (#1, Jan  3 2004, 13:57:08)
[GCC 3.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> class inch(float):
...     def __new__(cls, v):
...             return float.__new__(cls, v*0.0254)
...
>>> inch(12)
0.30479999999999996

See the difference?

Peter



More information about the Python-list mailing list