函数内部使用exec(astring)和astring中的变量定义无法在python 3中返回变量 [英] Function internally using exec(astring) with a variable definition inside astring can not return the variable in python 3

查看:87
本文介绍了函数内部使用exec(astring)和astring中的变量定义无法在python 3中返回变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个python 3函数,它接收一串命令,说'np.pi',然后尝试用该字符串定义一个变量。然后我尝试返回变量,但这是行不通的。

I have a python 3 function that takes a string of commands, say 'np.pi' and then tries to define a variable with that string. Then I try to return the variable, this however does not work.

input = np.pi
astring = 'funcD(funcC(funcB(funcA(input))))'

def function(astring):
  astring= 'variable = ' + astring
  exec(astring)
  return variable

In:  a = function(astring)
Out: NameError: global name 'variable' is not defined

似乎没有任何事情发生。我想要的是让该函数返回字符串中命令的输出。该字符串包含几个功能,他们之间的输入如下所示。我试着在返回后放入exec而不添加变量=,然后用函数(astring)调用函数,但那也不起作用。我相信我不能使用eval,因为我的字符串中有函数。

Nothing seems to have happened. What I would like is to have the function return the output of the command in the string. The string contains several functions who have each other as input like below. I tried putting the exec after return without adding the variable = and then call the function with a = function(astring) but that did not work either. I believe I cant use eval because my string has functions in it.

推荐答案

您没有说出您对答案的期望,所以我猜测:你想做这件事。

You didn't state what you expected from the answer, so I take a guess: You want to make this work.

使用 eval

def function(astring):
  astring= 'variable = ' + astring
  exec(astring)
  return eval('variable')

function('42')

按预期返回 42

或简单地剥离该分配:

Or simply strip that assignment:

def function(astring):
  return eval(astring)

这篇关于函数内部使用exec(astring)和astring中的变量定义无法在python 3中返回变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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