Python function parameters match the model (lower)

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 can function performed by the circulation or in the 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
复制代码

### ** and any parameter **is used to collect and pass keyword arguments to these parameters 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 general parameters, *parameters and **parameter complete the implementation of a more sophisticated way call.

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
复制代码

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

Guess you like

Origin blog.csdn.net/weixin_34234823/article/details/91463579