2013-01-13 80 views
85

函數參數中的裸星號有什麼作用?函數參數中的Python裸星號

當我看着鹹菜模塊,我看到:(http://docs.python.org/3.3/library/pickle.html#pickle.dump)

pickle.dump(obj, file, protocol=None, *, fix_imports=True) 

我知道一個前面參數的單個和雙個星號(對於可變數量的參數),但是這並不在前面。我很確定這與泡菜無關。這可能只是這種情況的一個例子。我只在將它發送給翻譯人員時才知道它的名字:

>>> def func(*): 
...  pass 
... 
    File "<stdin>", line 1 
SyntaxError: named arguments must follow bare * 

如果有問題,我使用python 3.3.0。

回答

85

Bare *用於強制調用者使用命名參數 - 因此,如果沒有以下關鍵字參數,則無法使用*作爲參數定義函數。

有關更多詳細信息,請參見this answerPython 3 documentation

+0

請注意,所有位置(未命名)參數,包括'* args',必須出現在裸*之前。 – BallpointBen

17

雖然原來的答案完全回答了問題,只是添加了一些相關信息。單個星號的行爲來自PEP-3102。引用相關章節:

The second syntactical change is to allow the argument name to 
be omitted for a varargs argument. The meaning of this is to 
allow for keyword-only arguments for functions that would not 
otherwise take a varargs argument: 

    def compare(a, b, *, key=None): 
     ... 

用簡單的英語,這意味着通過key的值,則需要明確地把它作爲key="value"