如何将函数作为参数? (蟒蛇)

时间:2010-12-08 18:04:58

标签: python lambda input scipy argparse

我正在编写一个程序来计算旋转实体的体积。第一步是计算积分。我为此使用了scipy.integrate,但我无法找到在命令行中输入等式的最佳方法。我原本打算添加一个等式x=x**2参数'关于:x | y'然后将函数作为lambda。不幸的是,argparse不会将lambda作为参数类型,并尝试使用字符串来构造一个lambda(f = lambda x: args.equation)只返回一个字符串(真的可以理解)。

这是我到目前为止所得到的:

import sys
import argparse
import math
from scipy import integrate

parser = argparse.ArgumentParser(description='Find the volume of the solid of rotation defined')
parser.add_argument('equation', help='continous function')
parser.add_argument('a', type=float, help='bound \'a\'')
parser.add_argument('b', type=float, help='bound \'b\'')
parser.add_argument('-axis', metavar='x|y', help='axis of revolution')
args = parser.parse_args()

def volume(func, a, b, axis=None):
  integral = integrate.quad(func, a, b)
  return scipy.py * integral

print volume(args.equation, args.a, args.b)

任何建议将不胜感激 感谢

2 个答案:

答案 0 :(得分:6)

如果绝对不担心允许用户运行任意Python代码的安全风险,那么您可以使用eval创建一个可调用对象:

volume(eval('lambda x: %s' % args.equation), args.a, args.b)

答案 1 :(得分:2)

您应该可以对从参数中获得的字符串使用eval()

>>> f = eval("lambda x: x**2")
>>> f(5)
25
相关问题