繁体   English   中英

如何使用python3 argparse将字符串值正确传递给用户定义的函数?

[英]How to correctly pass string value to user defined function using python3 argparse?

我使用割线方法编写了一个简短的程序来计算定义为可调用函数的各种公司现金流的内部收益率。 每个功能都以公司股票市场行情或史诗命名。 该程序使用以下命令行参数运行: ,并使用 argparse 来解析命令行参数。 示例:python3 SecantMethod.py grg 0.2 0.4 6. 当程序运行时,它产生一个“str object is not callable”错误,到目前为止我一直无法解决。 问题似乎与 argparse 传递所需现金流量史诗的方式有关。 删除所有 argparse 代码并插入一个简单的 print(SecantMethod(roo 0,1 0.2 6)) 语句会导致程序返回正确的速率和迭代值。

import argparse


def SecantMethod(f, x0, x1, d):

    c = 0
    e = 0.5*pow(10, -d)

    while abs(x1 - x0) > e:
        if f(x1) - f(x0) == 0:
            return 'Division by zero'

        x = x1 - f(x1)*(x1 - x0)/(f(x1) - f(x0))
        x0, x1 = x1, x
        c += 1

    return x, c

def grg(x):

    return -1000\
       +100.00/(1 + x)\
       +210.00/(1 + x)**2\
       +331.00/(1 + x)**3\
       +446.10/(1 + x)**4\
      +1610.51/(1 + x)**5
    # root = 27.97% (x = 0.27967730)

def roo(x):

    return -4000\
       +1200/(1 + x)\
       +1410/(1 + x)**2\
       +1875/(1 + x)**3\
       +1050/(1 + x)**4
    # root = 14.30% (x = 0.14299344)


def main():

    parser = argparse.ArgumentParser(description= 'Solves f(x) = 0, using the secant method.')

    parser.add_argument('f', type=str, help='function name')
    parser.add_argument('x0', type=float, help='first interval endpoint')
    parser.add_argument('x1', type=float, help='second interval endpoint')
    parser.add_argument('d', type=int, help='number of decimal places')

    args = parser.parse_args()

    if args.x0 == args.x1:
        print('\nInvalid input: x0 and x1 must be distinct values.')
        return
    if args.d < 0:
        print('\nInvalid input: d must be a positive integer.')
        return

    # print('\nRoot & number of iterations: ', SecantMethod(roo, 0.1, 0.2, 8))
    print('\nRoot & number of iterations: ', SecantMethod(args.f, args.x0, args.x1, args.d))

if __name__ == "__main__":
    main()

字符串'grg'与函数grg

处理此问题的一种方法是提供映射:

valid_functions = {
    'grg': grg,
    'roo': roo,
}
# ...
SecantMethod(valid_functions[args.f], ...)

暂无
暂无

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

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