473,326 Members | 2,438 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,326 software developers and data experts.

operator overloading

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 ?

Apr 4 '07 #1
10 2368
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

Apr 4 '07 #2
On Apr 4, 3:36 am, "looping" <kad...@gmail.comwrote:
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__.

Apr 4 '07 #3
On Apr 4, 12:41 pm, "7stud" <bbxx789_0...@yahoo.comwrote:
On Apr 4, 3:36 am, "looping" <kad...@gmail.comwrote:
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__.
Hmmm...after reading Ziga's post and doing some more testing, I don't
think __slots__ has anything to do with it.
Apr 4 '07 #4
On Apr 4, 12:41 pm, "7stud" <bbxx789_0...@yahoo.comwrote:
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.
Upon closer reading, it actually says that the name "__slots__" has to
be bound inside the class body for the slot restrictions to take
effect.

Apr 4 '07 #5

"Ziga Seilnacht" <zi************@gmail.comwrote in message
news:11**********************@e65g2000hsc.googlegr oups.com...
| 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

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.

tjr



Apr 4 '07 #6
On Apr 4, 4:55 pm, "Terry Reedy" <tjre...@udel.eduwrote:
"Ziga Seilnacht" <ziga.seilna...@gmail.comwrote in message

news:11**********************@e65g2000hsc.googlegr oups.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

Apr 4 '07 #7

<sj*******@yahoo.comwrote in message
news:11**********************@b75g2000hsg.googlegr oups.com...
| 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

Thanks. Bug report submitted
http://sourceforge.net/tracker/index...70&atid=105470
or
http://python.org/sf/1694663

Terry Jan Reedy

Apr 4 '07 #8
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 may, or may not be a bug, depending on ones interpretation.
int.__pow__ is a ternary operation while int.__add__ is binary. For a
Python function, like def __pow__(self, ...), the interpreter can't
properly check if the method takes the correct number of arguments, so
accepts it without question. But since int.__add__ is a slot wrapper the
interpreter can tell, and chokes. So it just falls back to using
int.__pow__.

Now for a more detailed explanation. Each Python type, and class, has a
vtable of C function pointers for all the operations the interpreter
understands. A type only defines functions for those operations it
supports. The remaining pointer are null. These functions are known as
slot functions, a slot being a C structure field in a Python object
instance (Types are instances too!). The int type has slot functions for
binary + and ternary ** for instance, but none for container [].

To make the slot mechanism visible to Python, allowing operator
overloading, generic wrapper slot functions and slot wrapper methods are
used. When a special method, such as __add__ or __pow__, is added to a
class, either in the class declaration or later by attribute assignment,
the corresponding slot is set to point to a generic wrapper that will
actually call the special method. When a builin type, like int, has a
type specific slot function for a particular operation, a corresponding
slot wrapper is added to the type that can call the slot function. So
not only can one define addition for a class by having an __add__ method
(via generic wrappers), but one can call the __add__ method on an int
(via slot wrappers).

Now for the specific case of myint. Not all slot functions are created
equal. The binary + slot function takes two arguments, the ternary **
slot function three. So int's corresponding __add__ and __pow__ slot
wrapper methods also differ. When subclassing int all goes well:

class myint(int):
pass

The myint class inherits int's slot functions for arithmetic, and those
functions can be called by int's slot wrappers, such as __add__ and
__pow__. But the following is unexpected:

myint.__pow__ = myint.__add__

Here __pow__ calls a slot function taking three arguments, __add__ calls
one taking two. What follows is probably unplanned, no exception is
raised. myint's ** slot function is not replaced with a generic wrapper
that will call the __pow__ method. Instead myint keeps the slot function
inherited from int. So myint may have a __pow__ method that adds, but it
is never called when doing a **.
Curiously C PyPy does what was expected:
>pypy-c.exe
Python 2.4.1 (pypy 1.0.0 build 41438) on win32
Type "help", "copyright", "credits" or "license" for more information.
>>>class MyInt(int):
..... pass
.....
>>>MyInt.__pow__ = MyInt.__add__
mi=MyInt(12)
mi**2
14
>>>>

Lenard Lindstrom
Apr 5 '07 #9
sj*******@yahoo.com wrote:
On Apr 4, 4:55 pm, "Terry Reedy" <tjre...@udel.eduwrote:
>"Ziga Seilnacht" <ziga.seilna...@gmail.comwrote in message

news:11**********************@e65g2000hsc.googleg roups.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
Apr 5 '07 #10
sj*******@yahoo.com wrote:
On Apr 4, 4:55 pm, "Terry Reedy" <tjre...@udel.eduwrote:
>"Ziga Seilnacht" <ziga.seilna...@gmail.comwrote in message

news:11**********************@e65g2000hsc.googleg roups.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

Apr 5 '07 #11

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

16
by: Edward Diener | last post by:
Is there a way to override the default processing of the assignment operator for one's own __value types ? I realize I can program my own Assign method, and provide that for end-users of my class,...
34
by: Pmb | last post by:
I've been working on creating a Complex class for my own learning purpose (learn through doing etc.). I'm once again puzzled about something. I can't figure out how to overload the assignment...
16
by: gorda | last post by:
Hello, I am playing around with operator overloading and inheritence, specifically overloading the + operator in the base class and its derived class. The structure is simple: the base class...
2
by: pmatos | last post by:
Hi all, I'm overloading operator<< for a lot of classes. The question is about style. I define in each class header the prototype of the overloading as a friend. Now, where should I define the...
67
by: carlos | last post by:
Curious: Why wasnt a primitive exponentiation operator not added to C99? And, are there requests to do so in the next std revision? Justification for doing so: C and C++ are increasingly used...
3
by: karthik | last post by:
The * operator behaves in 2 different ways. It is used as the value at address operator as well as the multiplication operator. Does this mean * is overloaded in c?
5
by: Jerry Fleming | last post by:
As I am newbie to C++, I am confused by the overloading issues. Everyone says that the four operators can only be overloaded with class member functions instead of global (friend) functions: (), ,...
3
by: y-man | last post by:
Hi, I am trying to get an overloaded operator to work inside the class it works on. The situation is something like this: main.cc: #include "object.hh" #include "somefile.hh" object obj,...
9
by: sturlamolden | last post by:
Python allows the binding behaviour to be defined for descriptors, using the __set__ and __get__ methods. I think it would be a major advantage if this could be generalized to any object, by...
8
by: Wayne Shu | last post by:
Hi everyone, I am reading B.S. 's TC++PL (special edition). When I read chapter 11 Operator Overloading, I have two questions. 1. In subsection 11.2.2 paragraph 1, B.S. wrote "In particular,...
0
by: DolphinDB | last post by:
Tired of spending countless mintues downsampling your data? Look no further! In this article, you’ll learn how to efficiently downsample 6.48 billion high-frequency records to 61 million...
1
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: Vimpel783 | last post by:
Hello! Guys, I found this code on the Internet, but I need to modify it a little. It works well, the problem is this: Data is sent from only one cell, in this case B5, but it is necessary that data...
0
by: jfyes | last post by:
As a hardware engineer, after seeing that CEIWEI recently released a new tool for Modbus RTU Over TCP/UDP filtering and monitoring, I actively went to its official website to take a look. It turned...
0
by: ArrayDB | last post by:
The error message I've encountered is; ERROR:root:Error generating model response: exception: access violation writing 0x0000000000005140, which seems to be indicative of an access violation...
1
by: PapaRatzi | last post by:
Hello, I am teaching myself MS Access forms design and Visual Basic. I've created a table to capture a list of Top 30 singles and forms to capture new entries. The final step is a form (unbound)...
1
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
1
by: Defcon1945 | last post by:
I'm trying to learn Python using Pycharm but import shutil doesn't work
1
by: Shællîpôpï 09 | last post by:
If u are using a keypad phone, how do u turn on JavaScript, to access features like WhatsApp, Facebook, Instagram....

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.