簡體   English   中英

有沒有辦法將可選參數傳遞給函數?

[英]Is there a way to pass optional parameters to a function?

Python 中是否有一種方法可以在調用函數時將可選參數傳遞給函數,並且在函數定義中有一些基於“僅當傳遞可選參數時”的代碼

Python 2 文檔, 7.6。 函數定義為您提供了幾種方法來檢測調用者是否提供了可選參數。

首先,您可以使用特殊的形式參數語法* 如果函數定義的形式參數前面有一個* ,則 Python 會使用與前面的形式參數(作為元組)不匹配的任何位置參數填充該參數。 如果函數定義有一個以**開頭的形式參數,則 Python 會使用與前面的形式參數(作為 dict)不匹配的任何關鍵字參數填充該參數。 該函數的實現可以檢查這些參數的內容,以查找您想要的任何“可選參數”。

例如,這里有一個函數opt_fun ,它接受兩個位置參數x1x2 ,並查找另一個名為“可選”的關鍵字參數。

>>> def opt_fun(x1, x2, *positional_parameters, **keyword_parameters):
...     if ('optional' in keyword_parameters):
...         print 'optional parameter found, it is ', keyword_parameters['optional']
...     else:
...         print 'no optional parameter, sorry'
... 
>>> opt_fun(1, 2)
no optional parameter, sorry
>>> opt_fun(1,2, optional="yes")
optional parameter found, it is  yes
>>> opt_fun(1,2, another="yes")
no optional parameter, sorry

其次,您可以提供某個值的默認參數值,例如調用者永遠不會使用的None 如果參數有這個默認值,你就知道調用者沒有指定參數。 如果參數有一個非默認值,你就知道它來自調用者。

def my_func(mandatory_arg, optional_arg=100):
    print(mandatory_arg, optional_arg)

http://docs.python.org/2/tutorial/controlflow.html#default-argument-values

我發現這比使用**kwargs更具可讀性。

為了確定是否傳遞了一個參數,我使用自定義實用程序對象作為默認值:

MISSING = object()

def func(arg=MISSING):
    if arg is MISSING:
        ...
def op(a=4,b=6):
    add = a+b
    print add

i)op() [o/p: will be (4+6)=10]
ii)op(99) [o/p: will be (99+6)=105]
iii)op(1,1) [o/p: will be (1+1)=2]
Note:
 If none or one parameter is passed the default passed parameter will be considered for the function. 

如果你想給一個參數賦予一些默認值,請在 () 中賦值。 像(x = 10)。 但重要的是首先應該強制參數然后是默認值。

例如。

(y, x = 10)

(x=10, y) 是錯誤的

您可以使用永遠不會傳遞給函數的內容為可選參數指定默認值,並使用is運算符檢查它:

class _NO_DEFAULT:
    def __repr__(self):return "<no default>"
_NO_DEFAULT = _NO_DEFAULT()

def func(optional= _NO_DEFAULT):
    if optional is _NO_DEFAULT:
        print("the optional argument was not passed")
    else:
        print("the optional argument was:",optional)

那么只要你不做func(_NO_DEFAULT)你就可以准確地檢測參數是否被傳遞,並且與接受的答案不同,你不必擔心 ** 符號的副作用:

# these two work the same as using **
func()
func(optional=1)

# the optional argument can be positional or keyword unlike using **
func(1) 

#this correctly raises an error where as it would need to be explicitly checked when using **
func(invalid_arg=7)

暫無
暫無

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

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