[Python-Dev] Subclasses vs. special methods

Walter Dörwald walter at livinglogic.de
Mon Jan 6 11:53:10 CET 2014


On 04.01.14 13:58, Serhiy Storchaka wrote:

> Should implicit converting an instance of int, float, complex, str,
> bytes, etc subclasses to call appropriate special method __int__ (or
> __index__), __float__, __complex__, __str__, __bytes__, etc? Currently
> explicit converting calls these methods, but implicit converting doesn't.
>
>>>> class I(int):
> ...     def __int__(self): return 42
> ...     def __index__(self): return 43
> ...
>>>> class F(float):
> ...     def __float__(self): return 42.0
> ...
>>>> class S(str):
> ...     def __str__(self): return '*'
> ...
>>>> int(I(65))
> 42
>>>> float(F(65))
> 42.0
>>>> str(S('A'))
> '*'
>>>> chr(I(65))
> 'A'
>>>> import cmath; cmath.rect(F(65), 0)
> (65+0j)
>>>> ord(S('A'))
> 65
>
> Issue17576 [1] proposes to call special methods for implicit converting.
> I have doubts about this.

Note that for explicit conversion this was implemented a long time ago. 
See this ancient thread about str/unicode subclasses and 
__str__/__unicode__:

    https://mail.python.org/pipermail/python-dev/2005-January/051175.html

And this bug report:

    http://bugs.python.org/issue1109424

> [...]

Servus,
    Walter



More information about the Python-Dev mailing list