2010-12-08 89 views
3

我正在編寫一個程序來計算旋轉實體的體積。這是計算積分的第一步。我爲此使用了scipy.integrate,但我無法弄清楚有什麼方程式的最佳方法(例如在命令行中輸入x=x**2。我本來計劃在x | y'方面添加一個參數,然後以功能作爲一個lambda。不幸的是,​​不會採取lambda作爲參數類型,並試圖使用一個字符串來構造一個lambda(f = lambda x: args.equation)只是返回一個字符串(可以理解真的)。如何將函數作爲參數? (Python)

這裏是我的」已經走到這一步:

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) 

任何意見可以理解 感謝

回答

6

如果是完全無法從讓用戶運行任意的Python代碼對安全隱患的擔憂,那麼你可以使用eval創建可調用對象:

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

謝謝。有沒有更安全的方法? – 2010-12-08 18:16:51

2

你應該能夠在你從你的論點得到字符串使用eval()

>>> f = eval("lambda x: x**2") 
>>> f(5) 
25 
相關問題