[Tutor] Learning about callbaks

Alan Gauld alan.gauld at btinternet.com
Wed Jan 2 14:25:28 CET 2008


"Michael Bernhard Arp Sørensen" <michaelarpsorensen at stevnstrup.dk> 
wrote

> I did some research, reading and test last night and I finally got 
> it
> working.

Sorry, but you didn't! However you are very nearly there...

class UserInput:
    def __init__(self):
        pass
    def test_callback(self, this_callback):
        print "testing the callback"
        this_callback

To actually use the callback you need to use parens:

this_callback()

But this won't work because of the problem below...

class Game:
    def __init__(self):
        self.ui = UserInput()
    def hello(self):
        print "hello world"
    def useUI(self):
        self.ui.test_callback(self.hello())

Here you do not pass the function object to your test_callback 
function,
you actually call it here! You bneed to pass the function as an object
then call it in the receiver

self.ui.test_callback(self, self.hello)   # no parens means treat as 
object

What you have done is executed the function(which prints the message
thus leading you to think it has worked) and passes the return 
vaklue(None)
to your test_callback. But since you never actually call the function 
there
(missing parens) there is no error message.

You can prove this by inserting a raw_input statement into
your test_callback before you use the callback. That way the
message should only appear after you hit return...

> I wanted to understand how a "parent" object could send a callback
> to a "child" object, and now I got it.

Nearly. You apply the parens when you want to execute the function
you omit parens when you want to treat the function as an object.
You need to swap your use of parens.

HTH,

-- 
Alan Gauld
Author of the Learn to Program web site
http://www.freenetpages.co.uk/hp/alan.gauld 




More information about the Tutor mailing list