Calling member functions?
Peter Wang
pzw1 at hotmail.com
Thu Dec 13 16:44:10 EST 2001
"David Dawkins" <david_j_dawkins at spamless.hotmail.com> wrote:
> class Handler:
> def Callback(self):
> print "Callback called"
> class Notifier:
> def __init__(self, object, method):
> self.m_object = object
> self.m_method = method
> def notify(self):
> ## Now what??
> self.m_method(self.m_object) ## naive attempt
> h = Handler()
> n = Notifier( h, h.Callback )
> h.notify() # I want this to do h.Callback() in effect
(i'll assume you mean n.notify in the last line.)
when you instantiate n with "h.Callback", you're assigning a *bound*
function reference to n.m_method. you can see this by just printing
out the value of n.m_method. you'll get something like:
<method Handler.Callback of Handler instance at 0x80dba14>
thus, when you call m_method(), you don't have to provide an instance
for the "self" variable because the function is already bound to an
instance (specifically, to h).
if you change your code a little bit to the following:
class Notifier:
def __init__(self, object, method):
self.m_object = object
self.m_method = method
def notify(self):
self.m_method(self.m_object) ## naive attempt
h = Handler()
n = Notifier(h, Handler.Callback)
n.notify()
this will also work. notice that here, n is instantiated with an
*unbound* function, named Handler.Callback (which is different from
h.Callback). in this case, if you want to call n.m_method(), you have
to provide an instance for the "self" parameter, so you have to pass
in self.m_object.
incidentally, if you print out the value of n.m_method in this
modified code, you get:
<unbound method Handler.Callback>
HTH,
peter
More information about the Python-list
mailing list