[Tutor] Learning about callbaks

ALAN GAULD alan.gauld at btinternet.com
Wed Jan 2 23:11:37 CET 2008


Yes, exactly like that. 
Well done, you are now callback aware :-)

Alan G.

----- Original Message ----
From: Michael Bernhard Arp Sørensen <michaelarpsorensen at stevnstrup.dk>
To: Alan Gauld <alan.gauld at btinternet.com>
Cc: tutor at python.org
Sent: Wednesday, 2 January, 2008 8:19:23 PM
Subject: Re: [Tutor] Learning about callbaks

Hi.

On Jan 2, 2008 6:36 PM, Alan Gauld <alan.gauld at btinternet.com> wrote:

Can you modify the program *without modifying the classes* to use an
ordinary function as the callback? Say this goodbye function:

def goodbye():
     print "goodbye world"

This should not require more than 5 lines of new code and no changes

to the
existing code. It could be done in 3...


Like this?:

class UserInput:

    def __init__(self):
        pass


    def test_callback(self, this_callback):
        print "testing the callback"

        this_callback()


class Game:
    def __init__(self):

        self.ui = UserInput()


    def hello(self):
        print "hello world"


    def useUI(self):
        self.ui.test_callback(self.hello)


def goodbye():

    print "goodbye world"

g = Game()

g.useUI()
g.ui.test_callback(goodbye)


It took me a couple of minutes to understand your challenge. :-) Then I remembered that "ui" is instantiated inside "g" and therefore callable with the right parameter.

Thank you very, very much. I enjoy a good challenge.


-- 
Med venlig hilsen/Kind regards

Michael B. Arp Sørensen
Programmør / BOFH
I am /root and if you see me laughing you better have a backup.



-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20080102/df62db45/attachment.htm 


More information about the Tutor mailing list