Python这是eval还是exec可以接受的用法?还有别的办法吗?

2024-04-20 10:56:35 发布

您现在位置:Python中文网/ 问答频道 /正文

我对Python相当陌生,一直在寻找一种调用函数的方法,该函数的名称由字符串和一个变量的连接组成,当用户选择其中一个选项时,变量会动态填充。在

示例:

我用一个菜单启动程序,这个菜单给用户一些选项(选择1、2、3或4)

如果用户选择1,变量xyz将填充一个元组或列表中的字符串。在

将这个字符串分配给变量后,我调用另一个函数来提供另一个选项。在

如果我得到选项1,我的代码将把xyzvarible附加到一个预定义的字符串中,这个字符串将形成一个函数名(下一个函数名将被调用)。在

if int(option) == 1:
#prefixfunc will be that predefined string that will be the prefix for every function  #to be called
    exec('prefixfunc'+xyz'()')
    #or
    #eval('prefixfunc_'+xyz'()')
    #for example, we have xyz as abc, then it calls function prefixfunc_abc()

它在代码中运行良好。我不认为这可能是一个责任的情况下,用户添加了一个不同的输入。因为变量是通过使用列表或元组中已定义的字符串来赋值的。在

我希望我已经说清楚了。在

为了更清楚:

^{pr2}$

Tags: 函数字符串代码用户列表forthat选项
3条回答

好吧,你可以那样做,但是既然有很多更好的方法,为什么要那样做呢?例如:

funcs = {1: func1, 2: func2, 3: func3, 4: func4}
option = int(raw_input("Enter selection: "))
option in funcs and funcs[option]()

这里的优点是,您不必为函数遵循任何特定的命名约定。如果选项1是“adda name”,那么您可以调用函数addname(),而不是func1()。这将使您的代码更容易理解。在

如果您直接知道这些方法的名称,那么就按照@kindall的建议去做。否则,可以使用getattr()获取调用方法,而不必使用eval()编译/求值。在

class ZZ(object):
  def fooBar(self):
    print(42)
  def barFoo(self):
    print(-42)

#now make a z
anInstance = ZZ()

#build up a dynamic string
string = 'foo' + 'Bar'

#fetch the attribute bound to string for the instance
method = getattr(anInstance, string)

#now execute the bound method/function (that's what the empty parens do)
method()

# out comes the following! Tada!
>>> 42

# we can inline a lot of this and just do things like
getattr(anInstance, 'bar' + 'Foo')()

# out comes the following! Again with the Tada...
>>> -42

为此,我将使用一个dict,它将字符串名称映射到函数。在

def test():
 print "yay"

funcs = { "test": test }
funcs["test"]()

这提供了一个更好的方法来实现这一点,并且您可以通过使用in操作符来测试是否要非常容易地执行函数。在

回答:你的例子对evalexec有用吗?我会说不。如果你认为{}是正确的答案,请查看你的解决方案,看看是否有更易于维护、更简单或更明确的方法来实现你的目标。在本例中,它将用户输入映射到基于特定用户输入调用的函数。在

相关问题 更多 >