[Tutor] Function assignment (was: Re: Function type?)
Jeff Shannon
jeff@ccvcorp.com
Wed Jun 11 13:43:24 2003
A few points...
># Function Description
>
>pipe = Item('pipe')
>def pipe_desc():
> if self.parent = player:
> return "In your hand."
> return "On the floor."
>pipe.desc = pipe_desc
>
Actually, this will *not* work. In your pipe_desc() function, you use
'self' -- but there's nowhere for that self to come from! You need to
actually have self in the argument list, i.e. 'def pipe_desc(self):
[...]' However, there's still one more trick needed. In order for
'self' to be given the right value when called as a method, you have to
tell Python that this is a method of your pipe object. I believe that
this can be done using the 'new' module's instancemethod() function.
>Which means there's this pipe_desc object floating around, and could
>accidentally be overwritten. So I have to force a naming convention, such
>as itemname_function. Which would work, but feels kludgy and isn't as
>elegant.
>
Actually, you don't need to worry about that. As long as you still have
a reference to the function object, the original reference can go away
or be overwritten without harm.
>>> def f():
... print "I'm here!"
...
>>> f()
I'm here!
>>> function = f
>>> del f
>>> f()
Traceback (most recent call last):
File "<interactive input>", line 1, in ?
NameError: name 'f' is not defined
>>> function()
I'm here!
>>>
So once you've assigned your function to pipe.desc, pipe_desc isn't
needed any more, and could even be re-used. Be careful about re-using
function names, though -- you need to be aware of when the def statement
is executed. You'd need to have the first function object assigned to a
different name before the second def statement creates a new function
object with the same name. This is where something like makeMsg() is
useful -- a new function is defined each time makeMsg() is called, and
you must assign that function to a name in order to hold on to it, so it
forces proper serialization of your function definitions.
Jeff Shannon
Technician/Programmer
Credit International