operator overloading

Steve Holden steve at holdenweb.com
Thu Apr 5 09:14:25 EDT 2007


sjdevnull at yahoo.com wrote:
> On Apr 4, 4:55 pm, "Terry Reedy" <tjre... at udel.edu> wrote:
>> "Ziga Seilnacht" <ziga.seilna... at gmail.com> wrote in message
>>
>> news:1175711246.488717.262560 at e65g2000hsc.googlegroups.com...
>> | This looks like a bug in Python. It works for all the other
>> | operators:
> [SNIP]
>> | >>> i ** 3
>> | 74088
>> |
>> | You should submit a bug report to the bug tracker:
>> |
>> |http://sourceforge.net/bugs/?group_id=5470
>>
>> Nice test.  I thought maybe __pow__ might be different in not having a
>> reverse form, but indeed, int has an __rpow__ method.
>>
>> Before submitting, make sure that this does not work in 2.5, and then say
>> so in the bug report.  In fact, copy the version/system info that the
>> interactive interpreter puts up when it starts.
> 
> FWIW:
> Python 2.5 (r25:51908, Jan 21 2007, 03:10:25)
> [GCC 3.4.6 20060404 (Red Hat 3.4.6-3)] on HOSTNAME_REDACTED
> Type "help", "copyright", "credits" or "license" for more information.
>>>> class MyInt(int):
> ...     __pow__ = int.__add__
> ...
>>>> i=MyInt(42)
>>>> i**3
> 74088
> 
Interestingly, Jython doesn't suffer from this drawback, which I suspect 
is due to special-casing of the __pow__ operator that was discussed 
quite recently on python-dev without anybody noticing this aspect of things.

C:\jython2.2b1>jython
[...]
 >>> class S(int):
...   pass
...
 >>> S.__pow__ = S.__add__
 >>> s = S(12)
 >>> s ** 2
14
 >>>

Note that it still doesn't work to override the *instance's* method.

regards
  Steve
-- 
Steve Holden       +44 150 684 7255  +1 800 494 3119
Holden Web LLC/Ltd          http://www.holdenweb.com
Skype: holdenweb     http://del.icio.us/steve.holden
Recent Ramblings       http://holdenweb.blogspot.com



More information about the Python-list mailing list