程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Python --- Application of variable parameters *args, **kwarg

編輯:Python

List of articles

  • Preface
  • One 、 Description of variable parameters
  • Two 、 Variable parameter packaging
  • Two 、 Variable parameter unpacking


Preface

When the parameter of a function is preceded by an asterisk * The time expression is a variable position parameter , Two asterisks ** Indicates variable keyword parameters

One 、 Description of variable parameters

You can package the parameters passed by the function ( Tuples tuple Or a dictionary dictionary), Can also break up ( Decompose into individual elements ), The packing and unpacking of tuples use a single star *, The dictionary is packed and disassembled with double line numbers **

Two 、 Variable parameter packaging

pack , Is any number of... That will be passed to the function ( It could be zero ) Non key parameters / Keyword parameters are packaged into a tuple / Dictionaries ( Tuples can only accept non keyword parameters , The dictionary can only accept keyword parameters )

The code is as follows ( Example ):

def param(*args, **kwarg):
for i in args:
print(i)
for i,j in kwarg.items():
print(j, j)
print('*' * 20)
if __name__ == '__main__':
param(1, 2, a=4, b=5)
param(2, 3, a=1, b=2, c=3)

Return results :

1
2
4 4
5 5
********************
2
3
1 1
2 2
3 3
********************
Process finished with exit code 0

Two 、 Variable parameter unpacking

Unpack , Is a list that will be passed to the function 、 Tuples or dictionaries are split into independent elements and assigned to parameter variables in functions ( Including ordinary position parameters , Key parameters , Tuples , Dictionary, i.e ** Key parameters )
The code is as follows ( Example ):

def param(*args, **kwarg):
for i in args:
print(i)
for i,j in kwarg.items():
print(j, j)
print('*' * 20)
if __name__ == '__main__':
a = (1, 2, 3)
b = [1, 16, 22]
c = {
'a':11, 'b':13}
param(a, c)
param(*a, **c)
param(b, c)
param(*b, **c)

Return results :

# explain :param(a, c) Output a and b
(1, 2, 3)
{
'a': 11, 'b': 13}
********************
# explain :param(*a, **c) Break up a and c
1
2
3
11 11
13 13
********************
# explain :param(b, c) Output b and c
[1, 16, 22]
{
'a': 11, 'b': 13}
********************
# explain :param(*b, **c) Break up b and c
1
16
22
11 11
13 13
********************

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved