Overriding the __new__ method

Christoph Groth cgroth at gmx.net
Sun Feb 8 12:20:31 EST 2004


Hello Peter,

Thank you for the quick answer.

Peter Otten <__peter__ at web.de> writes:

>> 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?

Sure, but I still don't understand why 12 is returned.  The essay
says:

"The version overriding __init__ doesn't work because the float type's
__init__ is a no-op: it returns immediately, ignoring its arguments."

According to my understanding, if float type's __init__ ignores its
arguments then the value of `arg' above should be ignored.  Instead,
the constructed object has the value 12.  Where is this 12 passed to
the object being constructed?  The only statement involved seems to be
the invocation of float.__init__ and there arg is said to be ignored.

Christoph
-------------- next part --------------
A non-text attachment was scrubbed...
Name: not available
Type: application/pgp-signature
Size: 238 bytes
Desc: not available
URL: <http://mail.python.org/pipermail/python-list/attachments/20040208/baea0eb7/attachment.sig>


More information about the Python-list mailing list