簡體   English   中英

有沒有一種簡單的方法可以在 python 函數中使用可選的輸出參數?

[英]Is there a simple way to have optional output arguments in a python function?

我想做類似以下的事情。

我想定義一個函數func(),如下:

def func(**kwargs):
    if 'a' in kwargs:
        a = funcA()
    if 'b' in kwargs:
        b = funcB()
    ...

或者

def func(**kwargs):
    if 'a' in kwargs:
        kwargs['a'] = funcA()
    if 'b' in kwargs:
        kwargs['b'] = funcB()
    ...

其中 funcA() 和 funcB() 在別處定義。 然后我想用可變數量的參數調用函數 func() :

>>> func(a = x)
>>> func(b = y)
>>> func(a = x, b = y)
...

這些調用應該為 x、y 等賦值。實現此目的的最佳方法是什么?

你不能像那樣通過賦值給參數來修改調用者的變量,你需要用return語句返回一個值,調用者可以重新賦值給變量。

def func(**kwargs):
    if 'a' in kwargs and 'b' in kwargs:
        return (funcA(kwargs['a']), funcB(kwargs['b']))
    elseif 'a' in kwargs:
        return funcA(kwargs['a'])
    elseif 'b' in kwargs:
        return funcB(kwargs['b'])

a = func(a = a)
b = func(b = b)
a, b = func(a = a, b = b)

更通用、可擴展的方法是返回字典。

def func(**kwargs):
    retval = {}
    if 'a' in kwargs:
        retval['a'] = funcA(kwargs['a'])
    if 'b' in kwargs:
        retval['b'] = funcB(kwargs['b'])
    return retval

a = func(a = a)['a']
b = func(b = b)['b']
vals = func(a = a, b = b)
a = vals['a']
b = vals['b']

您在調用func時使用了位置參數,但不會傳入**kwargs

相反,您也必須為func指定關鍵字參數。

像這樣:

def func(**kwargs):
    if 'a' in kwargs:
        funcA(kwargs['a'])
    if 'b' in kwargs:
        funB(kwargs['b'])

進而:

func(a='hello')
func(b='thing')
func(a='hello', b='thing')

請參閱位置和關鍵字參數的文檔。

作為一般方法,為了拒絕編寫多個if條件,您最好使用它們的相關函數創建一個參數字典,然后在預期參數已傳遞給函數調用者的情況下對相關函數進行分類:

def func(**kwargs):
    arg_dict = {'a': funcA, 'b': funcB}
    for arg, value in kwargs.items():
        try:
            yield arg_dict.get(arg)(value)
        except TypeError:
            # do stuff or just pass

此函數將返回一個生成器,其中包含參數的相關函數的值。

請注意,如果您不想傳遞參數的值而不是上述arg_dict ,則應使用arg_dict = {'a': funcA(), 'b': funcB()}並只yield arg_dict.get(arg)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM