[Tutor] Attaching methods to class instances
Zak Arntson
zak@harlekin-maus.com
Thu Jun 19 19:39:01 2003
Hello again, more weird object stuff. I've created a class Object which
not only allows dynamic attaching of attributes and methods. One of the
things I want to provide is the ability to attach both variables AND
methods (that return a variable) to an instance on the fly. For example:
###
pipe = Object()
pipe.give(name="Green Pipe",
desc="A filthy green pipe.",
a_weight=10)
print pipe.name()
print pipe.desc()
print pipe.weight
###
This would output the following:
###
Green Pipe
A filthy green pipe.
10
###
Now, I solved the problem, but it required the addition of a _dummy()
method. Here's the source:
###
class Object:
## ... other methods ...
def attach(self, func, name=None):
setattr(self,
name or func.__name__,
new.instancemethod(func, self, Object))
def give(self, **args):
for key in args:
if key.startswith('a_'):
if key[2:]:
setattr(self, key[2:], args[key])
else:
self.attach(self._dummy(args[key]), key)
def _dummy(self, value):
def f(self):
return value
return f
###
As you can see, I had to create a _dummy method. If I replaced
###
else:
self.attach(self._dummy(args[key]), key)
###
with
###
else:
def f(self):
return args[key]
self.attach(f, key)
###
The new method would ALWAYS return whatever the last value of args[key] was.
Blech. Hence the addition of _dummy. But is there a cleaner way to do this?
---
Zak Arntson
www.harlekin-maus.com - Games - Lots of 'em