Small problem when overloading member functions...

Peter Hansen peter at
Wed Jan 8 22:40:40 CET 2003

Sean wrote:
> Anyway, I have a setup where I
> initialize a class object within another class, and then have to
> overload one of the new object's functions:
> class A:
>   def __init__(self):
>     pass
>   def setFunction(self, fromFunc, toFunc):
>     fromFunc = toFunc

This line can only rebind the *local* variable called "fromFunc"
away from the value that was passed in, to the value bound to the
local variable called "toFunc".  It has no effect whatsoever
on the attributes of any instance of A, since the variables are
entirely local to the function...

Also, you are not *overloading* member functions.  That's a term
from other languages which refers to the ability to create 
multiple methods *with the same name* but with different type
signatures, and the compiler choses which one to call based on
the types of the arguments provided.  Since Python is dynamically
typed, it does not support this concept.  

I would say that you are perhaps *overriding* the methods, but
even that term is already used to refer to the case where a 
child class replaces the definition of a method in the parent
class with its own version, to extend the functionality.

Perhaps we should just refer to *replacing* or even, in Python
fashion, *rebinding* member functions (which I would call 
"methods", usually).

As for how you do it... use references to the *class* names
and not the instances:

in the myClass __init__ method, do this:

   a = A()
   a.setFunction('myPrint', myClass.newPrint)

and in the setFunction method, do this:

   setattr(self.__class__, fromFunc, toFunc)

Or did you really mean to replace the function in *only* the
one instance of the A class?  That takes a different approach,
which I can't recall off the top of my head.... using bound 


More information about the Python-list mailing list