Python *args,**kwargs 函数传递中 *args,**kwargs含义是什么
- 用来处理可变参数
- *ags被打包成tuple
- **kwaegs被打包成dict
def print_multiple_args(*args):
print(type(args),args)
for idx,val in enumerate(args):
print(idx,val)
print_multiple_args(‘a’,’b’,’c’)
<class ‘tuple’> (‘a’, ‘b’, ‘c’) 0 a 1 b 2 c
def print_kwargs(**kwargs):
print(type(kwargs),kwargs)
for k,v in kwargs.items():
print('{}:{}'.format(k,v))
print_kwargs(a=1,b=2)
<class ‘dict’> {‘a’: 1, ‘b’: 2} a:1 b:2
可以灵活控制,不确定参数。
def print_all(a,*args,**kwargs):
print(a)
if args:
print(args)
if kwargs:
print(kwargs)
print_all('hello','world',name = 'erfan')
def print_multiple_args(*args):
print(type(args),args)
for idx,val in enumerate(args):
print(idx,val)
print_multiple_args(*['a','b','c'])
def print_kwargs(**kwargs):
print(type(kwargs),kwargs)
for k,v in kwargs.items():
print('{}:{}'.format(k,v))
print_kwargs(**dict(a=1,b=2))
|