exec()在函数python3.x内部不起作用 [英] exec() not working inside function python3.x

查看:491
本文介绍了exec()在函数python3.x内部不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试运行此代码,但exec()似乎未在函数内部执行字符串:

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')

我收到的错误:

NameError                                 Traceback (most recent call last)
<ipython-input-23-099995c31c78> in <module>()
----> 1 abc('avdfbafadnf')

<ipython-input-21-80dc547cb34f> in abc(xyz)
      4         s = 'temp=' + i + '(word)'
      5         exec(s)
----> 6         print (temp)

NameError: name 'temp' is not defined

fn_lst是函数名称的列表,即:['has_at', 'has_num' ...]

fn_lst is a list of function names i.e: ['has_at', 'has_num' ...]

在这种情况下,请让我知道exec()的替代方案.

Please let me know an alternative to exec() if possible in such a scenario.

推荐答案

不要将exec与函数名一起使用,只需将函数对象保留在列表中即可:

Instead of using exec with function names, just keep the function objects in the list:

fn_lst = [has_at, has_num, ...]

并直接执行呼叫 :

def abc(xyz):
    for i in fn_lst:
        temp= i(xyz)
        print(temp)

这篇关于exec()在函数python3.x内部不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆