Here is a simple code illustrating the essence of a problem:
class test:
def __init__(self):
self.var = 0
def set(self, val):
self.var = val
print eval('map(lambda x: self.var*x, [1,2,3,4,5])')
f = test()
f.set(10)
It says
NameError: global name 'self' is not defined
I know many people don’t like eval but in my case I have to use it because it executes a math formula from the string entered by a user during programm execution.
Any suggestions is highly appreciated! Thanks in advance!
Try:
The odd
self=selfwill create a copy ofselffrom the outer context into the inner context (the “body” of the lambda expression).