[Tutor] Function assignment (was: Re: Function type?) [example:new.instancemethod]
Zak Arntson
zak@harlekin-maus.com
Thu Jun 12 14:35:02 2003
> On Wed, 11 Jun 2003, Jeff Shannon wrote:
>
> [warning: the following is very dynamic code; do we really want to do
> this? *grin*]
Of course! Actually, it's good to discuss that. A lot of times we'll write
hefty code, not realizing it isn't needed (and by "we" I mean "me"). After
this big exercise, I may decide NOT to incorporate dynamically-added
functions. But it's still a cool thing to know.
Using your way, I concocted this class:
###
import new
class PyFictObject:
def attach(self, func, name=None):
setattr(self,
name or func.__name__,
new.instancemethod(func, self, PyFictObject))
def msg(self, name, message):
def f(self, message):
return message
self.attach(f, name)
# sample usage
pipe = PyFictobject()
# First, use attach to add a function.
def desc(self):
return "Here's a pipeDesc function! It could be more complicated."
pipe.attach(desc)
# Second, use msg to add a "string" which is really a function
pipe.msg('name', 'big green pipe')
###
Unfortunately, the msg function isn't working at all. I can't figure it out!
>
> The only reason we're going through that dynamic route is because Zak's
> doing it that way. *grin* But perhaps the simpler approach better
> mimics what Inform does?
<SNIP>
> Here's a few questions I have: in Inform, do the two definitions above
> create templates for all kinds of pipes, or do they make single object
> instances?
The two definitions make a pair of object instances. Their class is Object.
> Does Inform allow the addition/attachment of different
> attributes to an 'Object' (like 'name' or 'description') after it's been
> created?
No. All properties (methods, lists, variables) and attributes (logicals)
must be defined _for all instances of every class_. The equivalent Python
code (if you defined things in advance) would be (well, the following code
is actually buggy, but you can see what I'm seeing):
###
class GameObject:
def name(self): pass #stub
def description(self): pass #stub
# OTHER STUFF, LIKE in_player METHOD
pipe = GameObject()
def name (self):
return 'pipe'
attach(pipe, name, 'name')
def description (self):
if self.in_player():
return 'pipe in your hand!'
return 'pipe on the floor.'
attach(pipe, name, 'name')
# pipe2 excluded, but you get the idea
###
--
Zak Arntson
www.harlekin-maus.com - Games - Lots of 'em