Python函數(shù)中*args和**kwargs來傳遞變長參數(shù)的用法
單星號形式(*args)用來傳遞非命名鍵可變參數(shù)列表。雙星號形式(**kwargs)用來傳遞鍵值可變參數(shù)列表。
下面的例子,傳遞了一個固定位置參數(shù)和兩個變長參數(shù)。
def test_var_args(farg, *args): print "formal arg:", farg for arg in args: print "another arg:", arg test_var_args(1, "two", 3)
結果如下:
formal arg: 1 another arg: two another arg: 3
這個例子用來展示鍵值對形式的可變參數(shù)列表,一個固定參數(shù)和兩個鍵值參數(shù)。
def test_var_kwargs(farg, **kwargs): print "formal arg:", farg for key in kwargs: print "another keyword arg: %s: %s" % (key, kwargs[key]) test_var_kwargs(farg=1, myarg2="two", myarg3=3)
執(zhí)行結果:
formal arg: 1 another keyword arg: myarg2: two another keyword arg: myarg3: 3
調(diào)用函數(shù)時,使用 *args and **kwargs
這種語法不僅僅是在函數(shù)定義的時候可以使用,調(diào)用函數(shù)的時候也可以使用
def test_var_args_call(arg1, arg2, arg3): print "arg1:", arg1 print "arg2:", arg2 print "arg3:", arg3 args = ("two", 3) test_var_args_call(1, *args)
執(zhí)行結果如下:
arg1: 1 arg2: two arg3: 3
鍵值對方式:
def test_var_args_call(arg1, arg2, arg3): print "arg1:", arg1 print "arg2:", arg2 print "arg3:", arg3 kwargs = {"arg3": 3, "arg2": "two"} test_var_args_call(1, **kwargs)
結果如下:
arg1: 1 arg2: two arg3: 3
相關文章
Python 完美解決 Import “模塊“ could not&n
這篇文章主要介紹了Python 完美解決 Import “模塊“ could not be resolved ...,本文給大家分享問題原因及解決方法,需要的朋友可以參考下2022-11-11selenium.webdriver中add_argument方法常用參數(shù)表
這篇文章主要介紹了selenium.webdriver中add_argument方法常用參數(shù)表,需要的朋友可以參考下2021-04-04Python實現(xiàn)softmax反向傳播的示例代碼
這篇文章主要為大家詳細介紹了Python實現(xiàn)softmax反向傳播的相關資料,文中的示例代碼講解詳細,具有一定的參考價值,感興趣的可以了解一下2023-04-04Python使用Matplotlib實現(xiàn)Logos設計代碼
這篇文章主要介紹了Python使用Matplotlib實現(xiàn)Logos設計代碼,具有一定借鑒價值,需要的朋友可以參考下。2017-12-12Python?SQLAlchemy與數(shù)據(jù)庫交互操作完整指南
SQLAlchemy 是一個強大的 Python 庫,用于數(shù)據(jù)庫操作,無論是簡單的數(shù)據(jù)存儲還是復雜的數(shù)據(jù)管理,SQLAlchemy 都提供了多種方法來處理數(shù)據(jù)庫,本文將全面介紹 SQLAlchemy的基本用法以及各種操作的示例代碼2024-01-01