2010-12-08 74 views
0

我編寫了一個程序來解決我的物理章節中遇到的問題,該章節採用所有給定的數據並盡其所能完成所有工作。我使用了一串長長的if語句來檢查哪些函數可以安全地調用(函數本身並不安全),但是我覺得必須有更好的方法來實現。根據輸入Python的不同功能

完整的代碼是here

這裏的罪犯的片段(argparse默認爲無):

# 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) 

謝謝!

+0

獲取您的代碼在這裏。它有助於。 – pyfunc 2010-12-08 18:14:44

+0

「安全」? 「不安全」?你的意思是什麼? – 2010-12-08 18:15:19

+0

我相信他意味着拋出異常。 – marr75 2010-12-08 18:19:10

回答

1

考慮到您的程序設計,您發現了一個不錯的方式來實現你想要做的事情。但我認爲你的程序設計有些可疑。

如果我理解正確,您允許用戶傳遞儘可能多或者少的參數,然後調用所有定義了哪些參數的函數。爲什麼不要求要麼傳遞所有參數,要麼要求在通話中命名其中一個函數?


如果你堅持這樣的設計,你可以嘗試以下方法:

  • 使功能dict - >必需的參數:

    {find_velocity: ("t", "ld"), ...} 
    
  • 環比字典和檢查你是否有每個屬性:

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

看來你想調用一個函數,然後在一些參數中傳遞它。在這種情況下,您可能根本不需要argparse。相反,嘗試使你想成爲第一個命令行參數的函數,然後把所有其他的參數作爲該函數的參數。

您可以使用sys.argv[1]訪問第一個參數,並使用sys.argv[2:]訪問所有其他參數。

然後,你可以這樣調用該函數:

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

假設你的函數在本地模塊中定義。

3

將函數放在一個列表中,然後過濾該列表,確保對於該函數中的每個變量名,這些參數不是無。

例子:

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 

不要抱着我在語法上的煤,只是讓我知道,如果我搞砸了的任何地方,我只試過部分的解釋。

相關問題