operator overloading

Ziga Seilnacht ziga.seilnacht at gmail.com
Wed Apr 4 20:27:26 CEST 2007


looping wrote:
> Hi,
> for the fun I try operator overloading experiences and I didn't
> exactly understand how it works.
>
> Here is my try:
> >>> class myint(int):
>
>         def __pow__(self, value):
>                 return self.__add__(value)
>
> >>> a = myint(3)
> >>> a ** 3
>
> 6
>
> OK, it works. Now I try different way to achieve the same result but
> without much luck:
>
> >>> class myint(int):
>         pass
> >>> myint.__pow__ = myint.__add__
>
> or:
>
> >>> class myint(int):
>
>         __pow__ = int.__add__
>
> or:
>
> >>> class myint(int):
>         pass
> >>> a.__pow__ = a.__add__
>
> but for every try the result was the same:>>> a = myint(3)
> >>> a ** 3
> 27
>
> Why it doesn't works ?

This looks like a bug in Python. It works for all the other
operators:

>>> class MyInt(int):
...     __sub__ = int.__add__
...     __mul__ = int.__add__
...     __div__ = int.__add__
...     __truediv__ = int.__add__
...     __floordiv__ = int.__add__
...     __mod__ = int.__add__
...     __lshift__ = int.__add__
...     __rshift__ = int.__add__
...     __and__ = int.__add__
...     __xor__ = int.__add__
...     __or__ = int.__add__
...     __pow__ = int.__add__
...
>>> i = MyInt(42)
>>> i + 3
45
>>> i - 3
45
>>> i * 3
45
>>> i / 3
45
>>> i // 3
45
>>> i % 3
45
>>> i << 3
45
>>> i >> 3
45
>>> i & 3
45
>>> i ^ 3
45
>>> i | 3
45
>>> i ** 3
74088

You should submit a bug report to the bug tracker:

http://sourceforge.net/bugs/?group_id=5470

Ziga




More information about the Python-list mailing list