【问题标题】:Python different functions depending on inputPython根据输入不同的功能
【发布时间】:2011-05-22 09:45:49
【问题描述】:

我为我的物理章节编写了一个程序来解决问题,它获取所有给定的数据并尽其所能。我使用了一长串 if 语句来检查哪些函数可以安全调用(函数本身并不安全),但我觉得必须有更好的方法来做到这一点。

完整代码是here

这是违规者的 sn-p(argparse 默认为 None):

# EVALUATE:
if args.t and args.ld:
    print 'Velocity:', find_velocity(args.t, args.ld)
if args.t and args.l and args.m:
    print 'Velocity:', find_velocity(args.t, args.l, args.m)
if args.l:
    print 'Longest possible standing wave length:', find_longest_possible_standing_wave_length(args.l)
if args.l and args.m and args.t and args.n:
    print 'Frequency of the standing wave with', args.n, 'nodes:', find_nth_frequency_standing_wave(args.t, args.n, args.l, args.m)
if args.s and args.t and args.n and args.l:
    print 'Frequency of', args.n, 'standing wave:', find_nth_frequency_standing_wave(args.t, args.n, args.l, velocity=args.s)
if args.ld and args.t and args.f:
    print 'Angular wave number: ', find_angular_wave_number(args.ld, args.t, args.f)
if args.p:
    print 'Difference in amplitude of twins:', find_amplitude_difference_of_twins(args.p)
if args.f:
    print 'Angular wave frequency:',  find_angular_wave_frequency(args.f)

谢谢!

【问题讨论】:

  • 在这里获取您的代码。它有帮助。
  • “安全”? “不安全”?什么意思?
  • 我相信他的意思是抛出异常。
  • @S.Lott,不要尝试/捕获,他们会接受垃圾值并继续推进,直到出现问题。
  • “往前推进,直到事情搞砸了”?你的意思是直到他们得到例外?那有什么问题?这就是事情应该运作的方式。请更新问题以明确定义“安全”和“不安全”。

标签: python arguments switch-statement exists


【解决方案1】:

将函数放在一个列表中,然后过滤该列表以确保对于该函数中的每个变量名称,这些参数不是无。

例子:

def func_filter(item, arguments):
    needed_args = item.func_code.co_varnames
    all(map(lambda x: getattr(arguments, x) , needed_args))

funcs = (find_velocity, find_nth_frequency_standing_wave)
funcs = filter(lambda x: func_filter(x, args), funcs)
#now execute all of the remaining funcs with the necessary arguments,
#similar to code in func filter

不要在语法上纠缠不清,如果我在哪里搞砸了,请告诉我,我只在解释器上尝试了部分内容。

【讨论】:

  • 我接受了 katrie b/c s/他先来找我,但您的回答也很有帮助。谢谢!
【解决方案2】:

鉴于您的程序设计,您已经找到了一种执行您想做的事情的不错的方法。但我认为你的程序设计有问题。

如果我理解正确,您允许用户根据自己的意愿传递尽可能多或尽可能少的参数,然后在定义了哪些参数的情况下调用所有有意义的函数。为什么不要求传递所有参数或在调用时命名其中一个函数?


如果您坚持这种设计,您可以尝试以下方法:

  • 创建一个dict 的函数 -> 所需参数:

    {find_velocity: ("t", "ld"), ...}
    
  • 遍历dict并检查你是否拥有每个属性:

    for func, reqs in funcs.items():
        args = [getattr(args, req) for req in reqs]
        if all(args):
            func(*args)
    

【讨论】:

  • 因为我想不出一个统一的命名方法来为各种函数命名。我可以让它遍历一个选项列表,但是作为终端中的工具它会失去很多功能。我不想要求所有参数,因为不是每个问题都涉及每个变量。
  • @Nona:好吧,请参阅编辑以了解如何稍微整理您的代码。
【解决方案3】:

您似乎想调用一个函数,然后将其传递给一些参数。在这种情况下,您可能根本不需要 argparse。而是尝试将您想要的函数作为第一个命令行参数,然后将其他所有内容作为该函数的参数。

您可以使用sys.argv[1] 访问第一个参数,使用sys.argv[2:] 访问所有其他参数。

然后你可以这样调用函数:

locals()[sys.argv[1]](*sys.argv[2:])

假设你的函数是在本地模块中定义的。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-03-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-23
    • 2019-07-11
    • 1970-01-01
    相关资源
    最近更新 更多