• Index

### 关于作者

#### 函数的参数

Python的函数定义非常简单，但灵活度却非常大。除了正常定义的必选参数外，还可以使用默认参数、可变参数和关键字参数，使得函数定义出来的接口，不但能处理复杂的参数，还可以简化调用者的代码。

### 默认参数

def power(x):
return x * x


>>> power(5)
25
>>> power(15)
225


def power(x, n):
s = 1
while n > 0:
n = n - 1
s = s * x
return s


>>> power(5, 2)
25
>>> power(5, 3)
125


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


def power(x, n=2):
s = 1
while n > 0:
n = n - 1
s = s * x
return s


>>> power(5)
25
>>> power(5, 2)
25


def enroll(name, gender):
print 'name:', name
print 'gender:', gender


>>> enroll('Sarah', 'F')
name: Sarah
gender: F


def enroll(name, gender, age=6, city='Beijing'):
print 'name:', name
print 'gender:', gender
print 'age:', age
print 'city:', city


>>> enroll('Sarah', 'F')
Student:
name: Sarah
gender: F
age: 6
city: Beijing


enroll('Bob', 'M', 7)


def add_end(L=[]):
L.append('END')
return L


>>> add_end([1, 2, 3])
[1, 2, 3, 'END']
['x', 'y', 'z', 'END']


>>> add_end()
['END']


>>> add_end()
['END', 'END']
['END', 'END', 'END']


Python函数在定义的时候，默认参数L的值就被计算出来了，即[]，因为默认参数L也是一个变量，它指向对象[]，每次调用该函数，如果改变了L的内容，则下次调用时，默认参数的内容就变了，不再是函数定义时的[]了。

def add_end(L=None):
if L is None:
L = []
L.append('END')
return L


>>> add_end()
['END']
['END']


### 可变参数

def calc(numbers):
sum = 0
for n in numbers:
sum = sum + n * n
return sum


>>> calc([1, 2, 3])
14
>>> calc((1, 3, 5, 7))
84


>>> calc(1, 2, 3)
14
>>> calc(1, 3, 5, 7)
84


def calc(*numbers):
sum = 0
for n in numbers:
sum = sum + n * n
return sum


>>> calc(1, 2)
5
>>> calc()
0


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


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


### 关键字参数

def person(name, age, **kw):
print 'name:', name, 'age:', age, 'other:', kw


>>> person('Michael', 30)
name: Michael age: 30 other: {}


>>> person('Bob', 35, city='Beijing')
name: Bob age: 35 other: {'city': 'Beijing'}
name: Adam age: 45 other: {'gender': 'M', 'job': 'Engineer'}


>>> kw = {'city': 'Beijing', 'job': 'Engineer'}
>>> person('Jack', 24, city=kw['city'], job=kw['job'])
name: Jack age: 24 other: {'city': 'Beijing', 'job': 'Engineer'}


>>> kw = {'city': 'Beijing', 'job': 'Engineer'}
>>> person('Jack', 24, **kw)
name: Jack age: 24 other: {'city': 'Beijing', 'job': 'Engineer'}


### 参数组合

def func(a, b, c=0, *args, **kw):
print 'a =', a, 'b =', b, 'c =', c, 'args =', args, 'kw =', kw


>>> func(1, 2)
a = 1 b = 2 c = 0 args = () kw = {}
>>> func(1, 2, c=3)
a = 1 b = 2 c = 3 args = () kw = {}
>>> func(1, 2, 3, 'a', 'b')
a = 1 b = 2 c = 3 args = ('a', 'b') kw = {}
>>> func(1, 2, 3, 'a', 'b', x=99)
a = 1 b = 2 c = 3 args = ('a', 'b') kw = {'x': 99}


>>> args = (1, 2, 3, 4)
>>> kw = {'x': 99}
>>> func(*args, **kw)
a = 1 b = 2 c = 3 args = (4,) kw = {'x': 99}


### 小结

Python的函数具有非常灵活的参数形态，既可以实现简单的调用，又可以传入非常复杂的参数。

*args是可变参数，args接收的是一个tuple；

**kw是关键字参数，kw接收的是一个dict。