def function_name(*arguments, **keywords):
pass
return something*arguments 就是參數識別字 (identifier) 前面加上一個星號,與 **keywords 參數識別字前面加上兩個星號,這是兩種不同的不定參數設定模式。前者 *arguments 會把多的參數當成一組序對 (tuple) ,後者 **keywords 則是會把多的參數當成一組字典 (dictionary) ,因此需額外提供參數名稱當 key 。
*arguments 與 **keywords 可以同時使用,但是任一函數只能有一個 *arguments 或 **keywords 。以下程式示範 *arguments
def hello(age, *name):
for n in name:
print("Hello,", n, "!")
print("You are", age, "years old.")
hello(13, "John", "Mary", "9527")
# 《程式語言教學誌》的範例程式
# http://pydoing.blogspot.com/
# 檔名:def14.py
# 功能:示範 Python 程式
# 作者:張凱慶
# 時間:西元 2010 年 12 月 執行結果如下

以下程式示範 **keywords
def hello(**name):
for n in name:
print("Hello", n, ", you're", name[n])
hello(one = "John", two = "Mary", three = "9527")
# 《程式語言教學誌》的範例程式
# http://pydoing.blogspot.com/
# 檔名:def15.py
# 功能:示範 Python 程式
# 作者:張凱慶
# 時間:西元 2010 年 12 月 執行結果如下

以下程式同時使用 *arguments 與 **keywords
def hello(*name, **age):
for n in name:
print("Hello,", n, "!")
for n in age:
print("You are", age[n], "years old.")
hello("John", "Mary", "9527", one = 13, two = 25, three = 33)
# 《程式語言教學誌》的範例程式
# http://pydoing.blogspot.com/
# 檔名:def16.py
# 功能:示範 Python 程式
# 作者:張凱慶
# 時間:西元 2010 年 12 月 執行結果如下

| 中英文術語對照 | |
|---|---|
| 函數 | function |
| 參數 | parameter |
| 參數列 | paramenter list |
| 識別字 | identifier |
| 序對 | tuple |
| 字典 | dictionary |
參考資料
http://docs.python.org/py3k/tutorial/controlflow.html
http://docs.python.org/py3k/reference/compound_stmts.html
http://docs.python.org/py3k/tutorial/controlflow.html
http://docs.python.org/py3k/reference/compound_stmts.html
沒有留言:
張貼留言