###### Python学习笔记三：函数

1、返回多个值

return x，y其实返回的是(x,y)。

2、函数的默认参数

...     L.append('END')
...     return L
...
['END']
['END', 'END']
['END', 'END', 'END']

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

3、可变参数

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

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

4、关键字参数

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

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

name: Adam age: 45 other: {'gender': 'M', 'job': 'Engineer'}

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

5、命名关键字参数

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

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

6、函数定义的例子

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

def f2(a, b, c=0, *, d, **kw):
print('a =', a, 'b =', b, 'c =', c, 'd =', d, 'kw =', kw)

>>> f1(1, 2)
a = 1 b = 2 c = 0 args = () kw = {}
>>> f1(1, 2, c=3)
a = 1 b = 2 c = 3 args = () kw = {}
>>> f1(1, 2, 3, 'a', 'b')
a = 1 b = 2 c = 3 args = ('a', 'b') kw = {}
>>> f1(1, 2, 3, 'a', 'b', x=99)
a = 1 b = 2 c = 3 args = ('a', 'b') kw = {'x': 99}
>>> f2(1, 2, d=99, ext=None)
a = 1 b = 2 c = 0 d = 99 kw = {'ext': None}

>>> args = (1, 2, 3, 4)
>>> kw = {'d': 99, 'x': '#'}
>>> f1(*args, **kw)
a = 1 b = 2 c = 3 args = (4) kw = {'d': 99, 'x': '#'}
>>> args = (1, 2, 3)
>>> kw = {'d': 88, 'x': '#'}
>>> f2(*args, **kw)
a = 1 b = 2 c = 3 d = 88 kw = {'x': '#'}

7、生成器yield

1, 1, 2, 3, 5, 8, 13, 21, 34, ...

def fib(max):
n, a, b = 0, 0, 1
while n < max:
print(b)
a, b = b, a + b
n = n + 1
return 'done'

def fib(max):
n, a, b = 0, 0, 1
while n < max:
yield b
a, b = b, a + b
n = n + 1
return

>>> fib(6)
<generator object fib at 0x7fe7ba7719b0>
>>> o=fib(6)
>>> next(o)
1
>>> next(o)
1
>>> next(o)
2
>>> next(o)
3
>>> next(o)
5
>>> next(o)
8
>>> next(o)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
StopIteration

>>> o=fib(6)
>>> def p(o):
...     while True:
...         try:
...             x=next(o)
...             print(x)
...         except StopIteration as e:
...             print('StopIteration')
...             break
...
>>> p(o)
1
1
2
3
5
8
StopIteration

8、返回函数

>>> def lazy_sum(*args):
...     def sum():
...         ax = 0
...         for n in args:
...             ax=ax+n
...         return ax
...     return sum
...
>>> f=lazy_sum(1,3,5,7,9)
>>> f
<function sum at 0x7fe7ba7867d0>
>>> f()
25

9、匿名函数lambda

>>> list(map(lambda x: x * x, [1, 2, 3, 4, 5, 6, 7, 8, 9]))
[1, 4, 9, 16, 25, 36, 49, 64, 81]

10、装饰器

import functools

def log(func):
@functools.wraps(func)
def wrapper(*args, **kw):
print('call %s():' % func.__name__)
return func(*args, **kw)
return wrapper

import functools

def log(text):
def decorator(func):
@functools.wraps(func)
def wrapper(*args, **kw):
print('%s %s():' % (text, func.__name__))
return func(*args, **kw)
return wrapper
return decorator

@functools.wraps(func)语句的功能是使func.__name__的值保持不变。

11、偏函数

>>> def func(a,b):
...     return a+b
...
>>> func('what\'s ','up')
"what's up"
>>> func(1,2)
3

>>> import functools
>>> func2=functools.partial(func,b='end')
>>> func2('it\'s ')
"it's end"

#### 数据分析学习笔记（三）－－numpy：内置函数（通用函数、数学与统计方法、集合）

2018-04-18 19:05:13

#### Python学习笔记

2010年02月23日 596KB 下载

#### python学习笔记

2018年04月24日 906KB 下载

#### OpenCV python 学习笔记(三)

2017-02-18 13:40:57

#### python 学习笔记资料

2018年01月23日 1.67MB 下载

#### Python3 学习笔记（十一）测试代码

2018-03-23 22:39:37

#### python学习笔记(三)函数

2017-04-08 15:54:08

#### Python学习笔记（三）：函数

2017-09-30 21:39:02

#### Python学习笔记（三）——函数

2017-03-29 01:59:32

#### cmake 学习笔记(六)

2011-04-22 15:12:00

Python学习笔记三：函数