# python函数——形参中的：*args和**kwargs

Note：多个实参，放到一个元组里面，以*开头，可以传递多个参数；**是形参中按照关键字传值吧多余的传值以字典的方式实现。

------------------------------------------手动分割线------------------------------------

*args：将实参中按照位置传值，多出来的值都给args，以元组方式实现。

def multiply(x, y):
print (x * y)

multiply(5, 4)

def multiply(x, y):
print (x * y)

multiply(5, 4, 3)

输出结果为：TypeError: multiply() takes 2 positional arguments but 3 were given

def multiply(*args):
z = 1
for num in args:
z *= num
print(z)

multiply(4, 5)
multiply(10, 9)
multiply(2, 3, 4)
multiply(3, 5, 10, 6)

20
90
24
900

def func(x,*args):
print(x)
print(args)

func(1,2,3,4,5) #1->x  2,3,4,5->args

1
(2, 3, 4, 5)

def func(x,y=1,*args):
print('x = ',x)
print('y = ',y)
print('args = ',args)

func(1,2,3,4,5) #1->x  2->y  3,4,5->args

x =  1
y =  2
args =  (3, 4, 5)

def func(x,*args,y=1):
print('x = ',x)
print('args = ',args)
print('y = ',y)

func(1,2,3,4,5) #1->x  2,3,4,5->args  1->y

x =  1
args =  (2, 3, 4, 5)
y =  1

------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------                   手动分割线          -------------------------------------------------

**kwargs：形参中按照关键字传值把多余的传值以字典的方式实现

def print_kwargs(**kwargs):
print(kwargs)

print_kwargs(kwargs_1="Shark", kwargs_2=4.5, kwargs_3=True)

{'kwargs_1': 'Shark', 'kwargs_2': 4.5, 'kwargs_3': True}

def print_values(**kwargs):
for key, value in kwargs.items():
print("The value of {} is {}".format(key, value))

print_values(my_name="Sammy", your_name="Casey")

The value of my_name is Sammy
The value of your_name is Casey

Note：**kwargs形成的字典不会按照函数的输入形式排序，字典格式是随机的。结果也有可能为：

The value of your_name is Casey
The value of my_name is Sammy

*******************

def func(x,**kwargs):
print('x = ',x)
print('kwargs = ',kwargs)

func(1,y=1,a=2,b=3,c=4) # y a b c -> kwargs

x =  1
kwargs =  {'a': 2, 'c': 4, 'b': 3, 'y': 1}

def func(x,*args,**kwargs):
print('x = ',x)
print('args = ',args)
print('kwargs = ',kwargs)

func(1,2,3,4,y=1,a=2,b=3,c=4) 

x =  1
args =  (2, 3, 4)
kwargs =  {'b': 3, 'c': 4, 'a': 2, 'y': 1}

def func(x,**kwargs,*args):
print('x = ',x)
print('args = ',args)
print('kwargs = ',kwargs)

func(1,y=1,a=2,b=3,c=4,2,3,4) 

SyntaxError: invalid syntax

def func(x,y=2,**kwargs):
print('x = ',x)
print('y = ',y)
print('kwargs = ',kwargs)

func(1,y=1,a=2,b=3,c=4) 

x =  1
y =  1
kwargs =  {'c': 4, 'a': 2, 'b': 3}

12-29 221

11-01 14万+
05-04 1万+
11-21 386
10-04 182
06-18 1万+
06-13 848
10-31 9611
07-31 170
01-01 678
02-26 4580