[Tutor] Function assignment (was: Re: Function type?)

Danny Yoo dyoo@hkn.eecs.berkeley.edu
Tue Jun 10 20:43:04 2003


> We can probably unify things a little more by making messages themselves
> functions, like this:
>
> ###
> >>> def makeMsg(m):
> ...     def f():
> ...         return m
> ...     return f
> ...
> >>> m1, m2 = makeMsg("hello"), makeMsg("testing!")
> >>> m1
> <function f at 0x8159384>
> >>> m2
> <function f at 0x815a2a4>
> >>> m1()
> 'hello'
> >>> m2()
> 'testing!'
> ###


> Yes, very possible.  The makeMsg() function above is an example of a
> function that itself generates function objects.  You might be able to
> employ the same function-constructing technique when attaching new
> description functions to your objects.  So something like:
>
>     pipe.desc = makeDescriptionMethod(...)
>
> should work; makeDescriptionMethod will look very similar to makeMsg(),
> except that it'll need to take in 'self', since it's a method.
              ^^^^^


Wow, that was slightly confusing to read.  *grin* Small clarification, by
"it", I don't mean makeDescriptionMethod() itself, but instead, I mean the
function that is being built by makeDescriptionMethod().  That is, instead
of:

###
def makeDescriptionMethod(generic_message, personal_message):
    def f():
    ...
###


we'd probably want to do something like:

###
def makeDescriptionMethod(generic_message, personal_message):
    def f(self):
    ...
###


So that the function that's being called has a way of grasping at the pipe
we pass it.  Once we have something like makeDescriptionMethod(), it
becomes very convenient to add dynamic methods like this:

    gandalf_pipe.desc = makeDescriptionMethod(
                        "A green pipe on the ground",
                        "A green pipe in your hands")


(Hmmm... but why would anyone pass a hot water pipe to someone else?
Wouldn't that hurt?  *grin*)



Talk to you later!