Calling member functions?

Duncan Booth duncan at NOSPAMrcp.co.uk
Thu Dec 13 07:51:16 EST 2001


"David Dawkins" <david_j_dawkins at spamless.hotmail.com> wrote in
news:U60S7.9819$hg1.986922 at news6-win.server.ntlworld.com: 

> I can't quite get this right. How can I give an object instance and a
> method as a callback for some other module/class to call at a later
> point? 

Generally you dont. You just pass the method on its own:

class  Handler:
    def Callback(self):
        print "Callback called"

class Notifier:
    def __init__(self, method):
        self.m_method = method

    def notify(self):
        self.m_method()

h = Handler()
n = Notifier(h.Callback)
n.notify()  # Calls h.Callback()


h.Callback is a bound method. If you call it, then it calls the Callback 
method on the h instance. What you were doing was attempting to use it as 
though it were an unbound method. Calls to h.Callback take no arguments.

Handler.Callback would be the unbound method. Calls to Handler.Callback 
take one argument. Your original code probably works if you pass in h and 
Handler.Callback, but usually it is cleaner to pass a single object for the 
callback rather than two.

A third option is to pass in h and the name of the callback method as a 
string and call it using getattr, but while this is sometimes useful it is 
generally messy.

-- 
Duncan Booth                                             duncan at rcp.co.uk
int month(char *p){return(124864/((p[0]+p[1]-p[2]&0x1f)+1)%12)["\5\x8\3"
"\6\7\xb\1\x9\xa\2\0\4"];} // Who said my code was obscure?



More information about the Python-list mailing list