FAQ

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...
I'm not quite sure to understand what you're trying to do, but I dont
see what is has to do with overloading...

First let have a look on your code :
class A:
def __init__(self):
pass >
def setFunction(self, fromFunc, toFunc):
fromFunc = toFunc
Why do you need to make this a method ? It could (and should IMHO) be
either a function or a static method. (hint : 'self' is not used)
def myPrint(self):
print 'Old'
>
>
class myClass:
def __init__(self):
a = A()
#a.setFunction(a.myPrint, self.newPrint)
Ok, this just can't work because a method *is not* just a function.
a.myPrint = self.newPrint
This is a more simple way to do it, and that ones work !-)
a.myPrint() >
def newPrint(self):
print 'New'
>
>
b = myClass()
>

Ok, now where are you overloading a function ?

Usually (please correct me if i'm wrong), "overloading" a function means
"having two (or more) functions with the same name but different
argument lists". This is a 'feature' of languages like C++ or Java, but
not of Python (where you could use some other way to achieve this).

What you're doing here is 'replacing' an instance method with another
one (I guess in Python's parlance, we should say 'rebinding').

If what you're trying to do is just that (replacing an instance method),
do it the simplest way (the one that is not commented in your code).

Now if you want to 'replace' a method for all existing instances of a
class, I leave it up to some __class__ Guru !-)

Laotseu

Search Discussions

Discussion Posts

Previous

Follow ups

Related Discussions

Discussion Navigation
viewthread | post
posts ‹ prev | 5 of 8 | next ›
Discussion Overview
grouppython-list @
categoriespython
postedJan 8, '03 at 8:34p
activeJan 10, '03 at 5:41a
posts8
users5
websitepython.org

People

Translate

site design / logo © 2022 Grokbase