dynamically inserting function into an object
John Roth
newsgroups at jhrothjr.com
Thu Jan 13 11:26:37 EST 2005
If what you want is to insert a method into an
instance, look at new.instancemethod.
John Roth
"michael" <michael.bierenfeld at web.de> wrote in message
news:f11c8440.0501130808.6c50a62b at posting.google.com...
> Hi,
>
> below is a snipplet that could be seen as a part of a spreadsheet with
> getter and setter properties and a way how to dynamically insert
> function to be used when setting the value of a "cell" instance
>
>
> import new
> import inspect
>
> class Cell (object):
>
> def __init__ (self, initialvalue = 0):
> self._func = None
> self.__value = initialvalue
>
> def setvalue (self, newvalue):
> if self._func:
> self.__value = self._recalculate (newvalue)
> else:
> self.__value = newvalue
>
> def getvalue (self):
> return self.__value
>
> def _recalculate (self, value):
>
> ret_value = self._func (value)
>
> return ret_value
>
> def delvalue (self):
> del self.__value
>
>
> value = property(getvalue, setvalue, delvalue, "I'm the 'value'
> property.")
>
> def curry(self, func, *args):
> self._func = new.function(func.func_code, func.func_globals,
> argdefs=args)
>
> func = property(curry, "I'm the 'func' property.")
>
> def func (value, firstcell, secondcell):
> return value + firstcell.value + secondcell.value
>
> cell0 = Cell (10)
> cell1 = Cell (20)
>
> curriedcell = Cell (100)
>
> print "uncurried initial %d " % (curriedcell.value)
>
> curriedcell.value = 60
>
> print "uncurried set %d " % (curriedcell.value)
>
> curriedcell.curry (func, cell0, cell1)
> curriedcell.value = 62
>
> print "curried set %d " % (curriedcell.value)
>
>
>
> Is there a better way to do this or am I totally on the wrong way ?
>
> Regards
>
> Michael
More information about the Python-list
mailing list