Python tutorials (Python learning route): Python function parameters match the model (under)

Python tutorials (Python learning route): Python function parameters match the model (under)

Any parameter *

When we function receives any number of parameters, or the number of parameters can not be determined, we can use * to define any number of parameters, when the function call, all parameters do not match the positions will be assigned a tuple, we function can be used by the circulation or index

def f(*args):
 # 直接打印元组参数
 print(args)
 print('-'*20)
 # 循环打印元组参数
 [print(i) for i in args]
 ...
# 传递一个参数
f(1)
print('='*20)
# 传递5个参数
f(1, 2, 3, 4, 5)
复制代码

Sample results:

(1,)
--------------------
1
====================
(1, 2, 3, 4, 5)
--------------------
1
2
3
4
5
复制代码

### arbitrary parameter **

And ** is used to collect these parameters and keyword arguments passed to a new dictionary that we can use in a function manner of dealing with these parameters dictionary

def f(**args):
 # 直接打印字典参数
 print(args)
 for key, value in args.items():
 print('{}: {}'.format(key, value))
f(a=1)
print('='*20)
f(a=1, b=2, c=3)
复制代码

Sample results:

{'a': 1}
a: 1
====================
{'a': 1, 'b': 2, 'c': 3}
a: 1
b: 2
c: 3
复制代码

Any mixing parameters

We can mix the general parameters and parameters * ** parameters complete the implementation of more complex invocation.

def f(a, *targs, **dargs):
 print(a, targs, dargs)
f(1,2,3, x=1, y=2)
复制代码

Sample results:

1 (2, 3) {'x': 1, 'y': 2}
复制代码

This can be seen not so intuitive way calling, and even some "confuse", then how when you call any of the parameters of the complex, is in the function call is more intuitive to understand?

Unpack parameters

We can function call, the direct use * and ** parameter passing, and then let the function automatically unpack it before unpacking sequence of similar, more intuitive use call.

def f(a, b, c, d):
 print(a, b, c, d)
f(1, *(2, 3), **{'d': 4})
复制代码

Sample results:

1 2 3 4
复制代码

More Python Python tutorials and learning routes will continue to update everyone Oh!


Reproduced in: https: //juejin.im/post/5cfe01d5f265da1bd1464c49

Guess you like

Origin blog.csdn.net/weixin_33916256/article/details/91459665