简体   繁体   English

Python的评估函数和传递参数?

[英]Python eval function and passing arguments?

How can I pass variables to an eval function? 如何将变量传递给评估函数?

I have tried some solutions posted here on SO as well as reading through the Python documentation 我已经尝试过在SO上发布的一些解决方案,以及通读Python文档

I have this section of code 'v' which I would like to reuse in another part of my code. 我有这部分代码“ v”,我想在我代码的另一部分中重复使用。 Here is a snippet: 这是一个片段:

 v = lambda r5, cdate : somefunc(r4, cdate) + math.exp(-t_3m*r1 - t_6m*r2 - t_1y*r3 - t_2y*r4 - retfrac(d[4], d[5], cdate, eoffset = 730)*r5) + \
                                                      math.exp(-t_3m*r1 - t_6m*r2 - t_1y*r3 - t_2y*r4 - t_3y*r5)

I would then like to do something to the likes of: 然后,我想对以下方面做一些事情:

w = "v(r5, cdate) + math.exp(-t_3m*r1 - t_6m*r2 - t_1y*r3 - t_2y*r4 - t_3y*r5)*(0"
# + some other expressions that I have to build up using a for loop since there is no closed form solution
func = lambda r6, cdate = i[30] : (five_year + (coupon_five_year/2)*(1-(ia_5y/.5))) - (coupon_five_year/2)*(eval(w)) - 100*math.exp(-t_3m*r1 - t_6m*r2 - t_1y*r3 - t_2y*r4 - t_3y*r5 - t_5y*r6)
                r6 = fsolve(func, xguess)[0]

When I try to evaluate this, I am getting an error that says: 当我尝试对此进行评估时,出现一条错误消息:

NameError: name 'v' is not defined

Once I remove v, from the expression for w, I then get a NameError for t_3m and it just waters through all of the variables. 从w的表达式中删除v后,我将得到t_3m的NameError,它会遍历所有变量。 Could someone please help me out? 有人可以帮我吗?

The eval function accepts two additional parameters to provide it with global and local variables. eval函数接受两个附加参数,以为其提供全局和局部变量。

You simply need to call it like this: eval(w,globals(),locals()) 您只需要这样调用它: eval(w,globals(),locals())

That's assuming the variable references made in the w string are all in scope when you call eval(). 假设调用eval()时,在w字符串中进行的变量引用全部在范围内。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM