please read the two code ,and i find the only different is printing the locals() or not. But one of them is wrong. Please help me , thanks
import numpy as np
class Solution:
def solve(self, f, a, b, n):
x = np.linspace(a,b,n)
# print(locals())
loc = locals()
fstr = '''
def fun(x):
return %s
''' % f
exec(fstr)
# print(locals())
fun = loc['fun']
y = fun(x)
print(x,y,sep = '\n')
a = Solution()
a.solve('x+1',-5,5,5)
In this code ,I didn't print the locals()
if I only print it and write '#' in front of "fun = loc['fun']" and "y = fun(x)" ,there is a key named 'fun' in the output of locals()
import numpy as np
class Solution:
def solve(self, f, a, b, n):
x = np.linspace(a,b,n)
# print(locals())
loc = locals()
fstr = '''
def fun(x):
return %s
''' % f
exec(fstr)
print(locals())
fun = loc['fun']
y = fun(x)
print(x,y,sep = '\n')
a = Solution()
a.solve('x+1',-5,5,5)
But in this code ,i can't find the key named 'fun' in the output of locals()
Traceback (most recent call last):
File "tmp.py", line 20, in <module>
a.solve('x+1',-5,5,5)
File "tmp.py", line 15, in solve
fun = loc['fun']
KeyError: 'fun'
All of this seem that "fun = loc['fun']" and "y = fun(x)" determine the output of locals()
but i think it is impossible for python that latter code can change the front code