[Tutor] Operator Overloading

jfouhy at paradise.net.nz jfouhy at paradise.net.nz
Tue Apr 5 00:56:40 CEST 2005


Quoting Kevin Reeder <reederk at comcast.net>:

> On Mon, 04 Apr 2005 21:14:21 +1200
> John Fouhy <jfouhy at paradise.net.nz> wrote:
> > Are you sure you've giving us all the code?
> No, I was trying to keep it simple. Anyway, here it is,

Fine, but always test the simplified version, unless you're absolutely certain
what you're throwing out!

This is the key to your problem:
 
>  def __getattr__(self, name):
>      MyListSub.calls = MyListSub.calls + 1
>      self.adds = self.adds + 1 
>      return MyList.__getattr__(self, name)

When you do 'A + [4, 5, 6]', python first calls A.__getattr__('__coerce__').

__coerce__ appears to be used to implement mixed-mode arithmetic (eg, adding an
int to a float).  Presumably, you could define your own numeric types; if you
then defined __coerce__, you could add, mulitply, etc. your type with the
builtin types.

I guess the reasoning looks something like this:
  "If both operands are the same, then call the appropriate __add__ method.
   Otherwise, look to see if either has a __coerce__ method.
      If so, try to use coerce to make them the same.
   Call the appropriate __add__ method."

I found this out by putting all your code into a file, and then using pdb.

ie: The file 'mylist.py' contains all your code, and ends with:

--------------------------------
A = MyListSub([1,2,3])
print A.stats()
print len(A)
print A.stats()
print A + [4, 5, 6]
print A.stats()
--------------------------------

I then run:  $ python /usr/lib/python2.4/pdb.py mylist.py

I put a break point on the line with 'A + [4, 5, 6]', and use the step command
to see what happens.  This immediately showed the call to __getattr__.

pdb is useful :-)

-- 
John.


More information about the Tutor mailing list