dynamically inserting function into an object

M

michael

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
 
J

John Roth

If what you want is to insert a method into an
instance, look at new.instancemethod.

John Roth
 
H

hanz

# class Cell(object):
# def __init__(self, initialvalue = 0):
# self._func = lambda x: x
# self.__value = initialvalue
#
# def setvalue (self, newvalue):
# self.__value = self._func(newvalue)
#
# def getvalue (self):
# return self.__value
#
# def delvalue (self):
# del self.__value
#
# value = property(getvalue, setvalue, delvalue, "I'm the 'value'
property.")
#
# def curry(self, func, *args):
# self._func = lambda x: func(x, *args)
 
M

michael.bierenfeld

*damn* it :) python rocks.
thx

michael .oO (resetting c/c++/java crap collected over the years)
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,484
Members
44,904
Latest member
HealthyVisionsCBDPrice

Latest Threads

Top