operator overloading
7stud
bbxx789_05ss at yahoo.com
Wed Apr 4 14:41:49 EDT 2007
On Apr 4, 3:36 am, "looping" <kad... at gmail.com> 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 ?
Look at the output of the following code:
class myint(int):
pass
print myint.__pow__
print myint.__add__
-----output:-----
<slot wrapper '__pow__' of 'int' objects>
<slot wrapper '__add__' of 'int' objects>
That shows that the names '__pow__' and '__add__' are __slots__.
According to Python in a Nutshell(p.102), a name that is a slot can
only be "bound"(i.e. assigned to) inside the class body. Any later
attempt to assign something to a name that is a slot has no effect.
In your case, I think that means that the only place you can assign
something to an int slot is inside the int class.
As an alternative, you could override __pow__(). Something like this:
class myint(int):
def __pow__(self, num):
return super(myint, self).__add__(num)
n = myint(3)
print n**3
---output:---
6
That doesn't attempt to reassign something to the slot int.__pow__;
rather it creates a new __pow__ name that hides int.__pow__.
More information about the Python-list
mailing list