# Python函数参数详解

Python函数定义时参数灵活，使用不同参数的组合不仅可以简化调用者的代码，还可以处理复杂的参数。

#### 位置参数

```def calc1(x):
return x * x

def calc2(x, n):
s = 1
for i in range(n):
s *= x
return s```

>>>calc2(2)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: calc2() takes exactly 2 arguments (1 given)

>>>calc2(2, 2, 2)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: calc2() takes exactly 2 arguments (3 given)

#### 默认参数

```def calc3(x, n = 2):
s = 1
for i in range(n):
s *= x
return s```

```def saveInfo(name, gender, age = 23, city = ‘HangZhou‘):
print(name, gender, age, city)

saveInfo(‘Alen‘, ‘M‘, city=‘Beijing‘)```

```def addEnd(L=[]):
L.append(‘END‘)
return L```

[‘END‘]
[‘END‘, ‘END‘]
[‘END‘, ‘END‘, ‘END‘]

```def addEnd(L=[]):
L.append(‘END‘)
print(id(L))
return L

#4518465224
#[‘END‘]
#4518465224
#[‘END‘, ‘END‘]```

```def addEnd(L=None):
L = [] if L == None else L
L.append(‘END‘)
print(id(L))
return L

#4518687688
#[‘END‘]
#4518688328
#[‘END‘]```

#### 可变参数

```def calc(numbers):
s = 0
for num in numbers:
s = s + num * num
return s```

>>>calc([1, 2, 3])
14
>>>calc([1, 2, 3])
30

```def calc(*numbers):
s = 0
for num in numbers:
s = s + num * num
return s

calc()
# 0
calc(1, 2, 3)
# 14
calc(1, 2, 3, 4)
# 30```

，如果已经有一个list或tuple，要调用可变参数怎么办呢？

>>>nums = [1, 2, 3]
>>>calc(nums[0], nums[1], nums[2])
14

>>>nums = [1, 2, 3]
>>>calc(*nums)
14

#### 关键字参数

```def user(name, age, **kw):
print(‘name:‘, name, ‘age:‘, age, ‘other:‘, kw)

user(‘Bob‘, 23)
# (‘name:‘, ‘Bob‘, ‘age:‘, 23, ‘other:‘, {})
user(‘Alen‘, 20, gender=‘M‘, job=‘Engineer‘)
# (‘name:‘, ‘Alen‘, ‘age:‘, 20, ‘other:‘, {‘gender‘: ‘M‘, ‘job‘: ‘Engineer‘})```

>>>extra = {‘city‘: ‘Beijing‘, ‘job‘: ‘Engineer‘}
user(‘Bob‘, 23, **extra)
name: Bob age: 23 other: {‘city‘: ‘Beijing‘, ‘job‘: ‘Engineer‘}

**extra表示把extra这个dict的所有key-value用关键字参数传入到函数的**kw参数，kw将获得一个dict。注意kw获得的dict是extra的一份拷贝，对kw的改动不会影响到函数外的extra。

#### 命名关键字参数

```def user(name, age, *, city, job):
print(‘name:‘, name, ‘age:‘, age, ‘city:‘, city, ‘job:‘, job)

user(‘Alen‘, 20, city=‘Beijing‘, job=‘Engineer‘)
# name: Alen age: 20 city: Beijing job: Engineer```

>>>user(‘Alen‘, 20, ‘Beijing‘, ‘Engineer‘)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: user() takes 2 positional arguments but 4 were given

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

```def user(name, age, *, city=‘Beijing‘, job):
print(name, age, city, job)

user(‘Bob‘, 22, job=‘Engineer‘)
# Bob 22 Beijing Engineer```

#### 参数组合

```def user(name, age = 20, *args, city = ‘Beijing‘, job, **kw):
print(name, age, args, city, job, kw)

user(‘Bob‘, 20, 120, job = ‘Engineer‘, gender = ‘M‘)
# Bob 20 (120,) Beijing Engineer {‘gender‘: ‘M‘}```

>>>args = (‘Bob‘, 20, 120) >>>kw = {‘job‘:‘Engineer‘, ‘gender‘:‘M‘} >>>user(*args, **kw) Bob 20 (120,) Beijing Engineer {‘gender‘: ‘M‘}