*args与**kwargs的使用及函数参数强制命名。

*args与**kwargs在装饰器,定义函数,类的继承初始化中经常会使用到。

虽然基本掌握使用了, 做个笔记,加强下记录。

* **记录:

def foo(a, b, *args, **kwargs):
    print(a, b)
    print(args)
    print(kwargs)


foo(1, 2, 3, 4, d=5, c='9')
print()
foo(1,2,3)
1 2
(3, 4)
{'d': 5, 'c': '9'}

1 2
(3,)
{}

从输出可以看出,*args与**kwargs在函数中args与kwargs的输出分别变成了元祖与字典

*与**不仅可以将输入的元素打包起来,同样也可以解包.

tuple_ven = (1, 2, 3, 4, 5,)
dict_ven = {'a': 'value_b', 'c': 'value_d'}


def fox(a=1, c=2):
    print(f'return is ===> {a},{c}')

fox(*tuple_ven[:2])
print()
fox(*dict_ven)
print()
fox(**dict_ven)
return is ===> 1,2

return is ===> a,c

return is ===> value_b,value_d

 解包过程中,其实最有意思的是第二部,给字典用*解包,直接给了两个key出来然后进行了赋值。

最后是一个有趣的赋值,可以通过*_来实现。

tuple_ven = (1, 2, 3, 4, 5,)
# 我想a=1 b=2 c=5
a, b, *_, c = tuple_ven
print(a, b, c)
print(_)
1 2 5
[3, 4]

 可以看到,*_接收了中间部分的参数,这样对于取值还是非常实用的。

最后*可以用在强制命名参数。

def foy(key1, *_, key2, key3):
    print(key1, key2, key3)
foy(7, 324, 3, 4, 3, 345, 34, key2=8, key3=9)
7 8 9

 在*_后面的所有参数必须通过关键字赋参,否则报错。*_可以接受任意长度的参数,实际使用中,可以直接使用*,前面的参数按照实际标准填写,后面的参数必须通过关键字赋参。

def foy(key1, *, key2, key3):
    print(key1, key2, key3)


foy(7, key2=3, key3=9)
7 3 9

最后这种情况,参数数量还是指定的,但*后面的参数必须通过关键字赋参,这个就是所谓的通过*的强制名称方法。

猜你喜欢

转载自www.cnblogs.com/sidianok/p/11925584.html
今日推荐