Small problem when overloading member functions...

Jack Diederich jack at performancedrivers.com
Wed Jan 8 22:05:15 CET 2003


On Wed, Jan 08, 2003 at 12:34:01PM -0800, Sean wrote:
> I'm a little new to the language, so please excuse me if I'm missing
> something obvious.  I've run into (what looks like) a strange
> inconsistency in the language.  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:
> 
> BEGIN SAMPLE CODE:
> 
> class A:
>   def __init__(self):
>     pass
>     
>   def setFunction(self, fromFunc, toFunc):
>     fromFunc = toFunc
>     
>   def myPrint(self):
>     print 'Old'  
> 
> 
> class myClass:
>   def __init__(self):
>     a = A()
> 
>     #a.setFunction(a.myPrint, self.newPrint)
>     a.myPrint = self.newPrint
> 
>     a.myPrint()
> 
>   def newPrint(self):
>     print 'New'
> 
> 
> b = myClass()
> 
> 
> END SAMPLE CODE
> 
> The code above works fine, and prints out 'New' like it should. 
> However, when I try to use the commented line (a.setFunction...)
> instead of (a.myPrint = self.newPrint), the a.myPrint function is not
> getting overloaded and still prints out 'Old'.  It seems to me that
> since I'm passing both method instance objects to a.setFunction(),
> there should be no problem overloading them.  Is there a way I can do
> this with a function call?  It's important for this system to have a
> generic method for overloading functions...


The effect you are going for is regular inheritence,

class A:
  def __init__(self):
    self.myPrint()

  def myPrint(self):
    print 'Old'

class myClass(A):
  def __init__(self):
    A.__init__(self)
    
  def myPrint(self):
    print 'New'

b = myClass()
g = A()

will print
New
Old

-jackdied





More information about the Python-list mailing list