class TestClass(object):
def __init__(self):
self.value = 100
self.x = lambda: self.value.__add__(100)
self.run()
def run(self):
self.x()
print self.value
t = TestClass()
#Output: 100
I would like to able to define a lambda function such as the one in TestClass and have it alter an instance variable. It would seem that the way the lambda is constructed means that it does not modify the original value. I suspect that this to do with Python’s reference strategy which I do more or less understand.
So accepting the flaws in what I have done, is there a similar way to get similar functionality? I ultimately need to define many methods like x and intend to keep them in a dictionary as they will form a simple instruction set. As far as I can tell I need either to use lambdas or exec to do what I want.
__add__is not inplace, so the return value ofTestClass.xisself.value + 100, butself.valueis not altered. Try this:Use the setattr to increment the value while still using a lambda. Beware however, lambda’s in python are one of its worst features. However, both methods work.
Edit
Just remebered something that you might find usefull! The standard library has a module called operator which implements standard operators as functions. If you plan on using lambdas a lot, you might like to investigate it.