I am trying to run this code but it seems that the exec() is not executing the string inside the function:
def abc(xyz):
for i in fn_lst:
s = 'temp=' + i + '(xyz)'
exec(s)
print (temp)
abc('avdfbafadnf')
The error I am receiving:
NameError Traceback (most recent call last)
in ()
----> 1 abc('avdfbafadnf')
in abc(xyz)
4 s = 'temp=' + i + '(word)'
5 exec(s)
----> 6 print (temp)
NameError: name 'temp' is not defined
fn_lst is a list of function names i.e: ['has_at', 'has_num' ...]
Please let me know an alternative to exec() if possible in such a scenario.
解决方案
Instead of using exec with function names, just keep the function objects in the list:
fn_lst = [has_at, has_num, ...]
and perform the call directly:
def abc(xyz):
for i in fn_lst:
temp= i(xyz)
print(temp)