Python | *args & **kwargs
*args和**kwargs主要是为了方便传递参数,*args是一个元组,**kwargs是一个词典,都支持类似可变参数传参。
注意
- *args和**kwargs同时出现,*args必须在前面
def demo_args(first, *args):
print(first)
print(type(args))
for arg in args:
print(arg)
def demo_kwargs(first, **kwargs):
print(first)
print(type(kwargs))
for key, val in kwargs.items():
print(key, val)
def demo_args_kwargs(first, *args, **kwargs):
print(first)
print(type(args))
for arg in args:
print(arg)
print(type(kwargs))
for key, val in kwargs.items():
print(key, val)
if __name__ == '__main__':
demo_args("This is *args", 1, 2, 3, 4)
print("--------------------------------")
demo_kwargs("This is **kwargs", name="yimt", age=123)
print("--------------------------------")
demo_args_kwargs("This is *args and **kwargs", 1, 2, 3, name="yimt", age=123)
Output
This is *args
<class 'tuple'>
1
2
3
4
--------------------------------
This is **kwargs
<class 'dict'>
name yimt
age 123
--------------------------------
This is *args and **kwargs
<class 'tuple'>
1
2
3
<class 'dict'>
name yimt
age 123