2014-09-13 25 views
0

當我們編寫函數時,我有一個關於如何定義可選關鍵字的問題。如果滿足其他條件,例如關鍵字make_plot將是True,那麼我們如何確定將需要的關鍵字,那麼用戶需要爲該功能提供plot_dir關鍵字?我們如何定義一個函數的可選關鍵字?

回答

2

如果您有複雜的邏輯,用於確定需要哪些關鍵字參數,哪些是可選的,但最好是使用

def my_function(**kwargs): 

kwargs僅僅是傳統簡單地接受任意關鍵字參數;名稱可以是任何東西,只要它的前綴爲**,並且在之後出現所有其他參數)。

既然您的函數將接受任何參數,您可以在函數內處理它們。這裏是將

  • 拒絕比ab,或c
  • 其他任何關鍵字參數的一個例子使a必需的參數
  • 使b可選
  • 如果bTrue,然後c必須1到10之間的整數;否則,c被忽略

她是函數

def my_function(**kwargs): 
    try: 
     a_value = kwargs.pop('a') 
    except KeyError:    
     raise TypeError("Missing required keyword argument 'a'") 

    b_value = kwargs.pop(b, False) 
    if b_value is True: 
     try: 
      c_value = int(kwargs.pop('c')) 
      if not (1 <= c_value <= 10): 
       raise ValueError 
     except KeyError: 
      raise TypeError("Must use keyword argument 'c' if 'b' is True") 
     except ValueError: 
      raise ValueError("'c' must be an integer between 1 and 10!") 

    try: 
     # Are there anymore keyword arguments? We don't care which one we get 
     x = next(iter(kwargs)) 
    except StopIteration: 
     # Good, nothing besides a, b, or c 
     pass 
    else: 
     raise TypeError("Unrecognized keyword argument '{0}'".format(x)) 

    # Now do what my_function is supposed to with a_value, b_value, c_value 

爲了解決您的評論,想象它僅適用於plot_dir檢查make_plot發現一個簡單的函數。 (我們更加鬆懈,因爲我們會忽略plot_dir如果make_plot丟失,而不是萎靡不振其作爲一個錯誤。)

def plot(**kwargs): 
    if 'make_plot' in kwargs: 
     plot_dir = kwargs.get('plot_dir', "/default/plot/dir") 
     # save or otherwise process the value of kwargs['make_plot'] 
+0

你的榜樣應該怎麼看起來像如果這兩個'make_plot'和'plot_dir'將是可選的,但'plot_dir'將與關於'make_plot'的決定有關? – Dalek 2014-09-13 13:53:28

1

對於你的第一個問題,看看the tutorial

對於第二個問題,那不是你怎麼做的。使plot_dir爲可選參數,默認爲None,並在函數的開頭檢查是否爲plot_dir is not None

def plot(plot_dir=None): 
    if plot_dir is not None: # an argument was provided 
     do_some_plots(plot_dir) 
    else: 
     do_something_else() 
相關問題