# *args,**kwargs 可变参数 关键字参数 命名关键字参数 区别 用法

## 1.可变参数的用法两种

def calc(*numbers):
sum = 0
for n in numbers:
sum = sum + n * n
return sum
#笨方法
>>> nums = [1, 2, 3]
>>> calc(nums[0], nums[1], nums[2])
14

#聪明方法,可以在list或tuple前面加一个*号，把list或tuple的元素变成可变参数传进去
>>> nums = [1, 2, 3]
>>> calc(*nums)
14

## 2.关键字参数用法也有两种

def person(name, age, **kw):
print('name:', name, 'age:', age, 'other:', kw)
#笨方法
>>> extra = {'city': 'Beijing', 'job': 'Engineer'}
>>> person('Jack', 24, city=extra['city'], job=extra['job'])
name: Jack age: 24 other: {'city': 'Beijing', 'job': 'Engineer'}
#聪明方法 用**extra表示把extra这个dict的所有key-value用关键字参数传入到函数的**kw参数，kw将获得一个dict，注意kw获得的dict是extra的一份拷贝，对kw的改动不会影响到函数外的extra
>>> extra = {'city': 'Beijing', 'job': 'Engineer'}
>>> person('Jack', 24, **extra)
name: Jack age: 24 other: {'city': 'Beijing', 'job': 'Engineer'}

## 3.命名关键字参数

def person(name, age, *, city, job):
print(name, age, city, job)

>>> person('Jack', 24, city='Beijing', job='Engineer')
Jack 24 Beijing Engineer

def person(name, age, *args, city, job):
print(name, age, args, city, job)

>>> person('Jack', 24, 'Beijing', 'Engineer')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: person() takes 2 positional arguments but 4 were given

def person(name, age, *, city='Beijing', job):
print(name, age, city, job)

>>> person('Jack', 24, job='Engineer')
Jack 24 Beijing Engineer

def person(name, age, city, job):
# 缺少 *，city和job被视为位置参数
pass
02-11 4668

04-13 1万+
01-06 684
06-05 1万+
02-01 941
02-20 4201
03-12 176
07-23 460
08-22 2099
07-10 530