*args和**kwargs传参的注意点

mac2022-06-30  23

传参的时候,字典格式的形参2种写法.

如下方示例

def aa(**kwargs): print(kwargs) # 第一种 等式写法 aa(name = "alex") #第二种字典键值对加**写法 aa(**{"name":"alex"})

  

列表传参 注意点 1 def test(*args): 2 print(args,"参数个数为%s"%len(args)) 3 str = [1, 2, 3, 4] 4 5 test(str) #输出结果([1, 2, 3, 4],) 参数个数为1 6 test(*str) #输出结果(1, 2, 3, 4) 参数个数为4

 

 

传形参时候,test(str)是将列表整体作为一个数据传入.而test(*str) 是将str作为一个列表传入.

所以前者用len函数输出为1,而后者作为列表传入则显示有4个元素

一个装饰器例子如下:

1 def zsq(func): 2 def wrapper(*args): 3 import re 4 v = func(*args) 5 ret = [] 6 for i in args: 7 ret.append(re.findall("\d+",i)) 8 return ret 9 10 return wrapper 11 @zsq 12 def a(*args): 13 print(*args) 14 str = ["a88d66e3a","wwa665wwa"] 15 print(a(*str))-----------------------------------------------------  输出结果为

a88d66e3a wwa665wwa[['88', '66', '3'], ['665']]

 

 

转载于:https://www.cnblogs.com/Young-shi/p/11277440.html

相关资源:JAVA上百实例源码以及开源项目
最新回复(0)