# Python核心笔记2- yield 函数创建生成器方式

XAMPP案例 469浏览

1、生成器

1.1 创建生成器方式1

``````#  原有方式
````test_list = [x*2 for x in range(5)]  # 执行后test_list : [0, 2, 4, 6, 8]````
``````#  生成器
``````test_gen = (x*2 for x in range(5))  # 执行后test_gen : <generator object <genexpr> at 0x106d2c820>
``````#  生成器的打印
``````next(test_gen)  # 执行后打印 0
``````next(test_gen)  # 执行后打印 2
````next(test_gen)  # 执行后打印 3````
``````#  遍历test_gen
``````for x in test_gen:
````    print(x)  # 打印 0 2 4 6 8````

1.2 创建生成器方式2

``````#  斐波那契数列， 原有写法
``````def fib(times):
``````    n = 0
``````    a,b = 0,1
``````    while n < times:
``````        print(b)
``````        a,b = b, a+b
``````        n += 1
``````    return True
``````
``````fib(5) # 打印结果：1, 1, 2, 3, 5, 8
``````
``````# 斐波那契， 生成器方式
``````def fib(times):
``````    n = 0
``````    a,b = 0,1
``````    while n < times:
``````        yield b
``````        a,b = b, a+b
``````        n += 1
``````    return True
``````
`````` obj_fit = fib(5)
``````
`````` #  逐次d打印
`````` next(obj_fit)  # 打印结果：1
`````` next(obj_fit)  # 打印结果：1
`````` next(obj_fit)  # 打印结果：2
``````
`````` #  打印返回的迭代器
`````` for x in obj_fit:
````     print x   # 打印结果 1, 1, 2, 3, 5, 8   ````

yield相当于 return 返回一个值，并且记住这个返回的位置，下次迭代时，代码从yield的下一条语句开始执行。

1.3 send方法

.send() 和next()一样，都能让生成器继续往下走一步（下次遇到yield停），但send()能传一个值，这个值作为yield表达式整体的结果。

``````def test():
``````  i = 0
``````  while i < 5:
``````    temp = yield i
``````    print(temp)
``````    print(i)
``````    i += 1
``````
``````t=test()
``````next(t)
``````t.send('test')
``````next(t)
````# 代码执行结果：hshs 0 None 1````

2、迭代器

2.1 可迭代对象

2.2 是否可迭代

````from collections import Iterable````
````print (isinstance([], Iterable))  # 打印 True````

2.3 迭代器

``````print(isinstance((x for x in range(10)), Iterator)) # 打印ture
````print(isinstance([], Iterator)) # 打印false````

``print(isinstance([], Iterator)) # 打印true``

3、闭包

``````def test_bb(numa):
``````
``````  def test_inner(numb):
``````    return numa + numb
````  return test_inner````
``````tb = test_bb(10)  # tb指向test_inner
``````result = tb(5)  # 调用test_inner
````print(result) # 打印 15````

3.1 实例

``````def line_conf(a, b):
``````    def line(x):
``````        return a*x + b
````    return line````
``````line1 = line_conf(100,100)
``````line2 = line_conf(100,100)
````line1(10)``line2(20)````

4、装饰器

4.1 简单装饰器

``````def check(func):
``````  def wrapper():
``````    print('---check---')
``````    func()
````  return wrapper````
``````@check
``````def login():
``````  print('login')
``````
````login() # 打印 ---check---  login````

4.2 多个装饰器

@check_one

@check_two

``````def check_one(func):
``````  def wrapper():
``````    print('---check_one---')
``````    func()
````  return wrapper````
``````def check_two(func):
``````  def wrapper():
``````    print('---check_two---')
``````    func()
````  return wrapper````
``````@check_one
``````@check_two
``````def login():
``````  print('login')
``````
````login() # 打印 ---check_one---  ---check_two---  login ````

4.3 带参数装饰器

``````def check(user):
``````  def outwrapper(func):
``````    def wrapper(*args, **kwargs):
``````      if user == 'admin':
``````        print('---check admin---')
``````      else:
``````        print('---check other---')
``````      func(*args, **kwargs)
``````    return wrapper
````  return outwrapper````
``````@check(user='admin')
``````def login(name, password):
````  print('Name:%s Pass:%s' % (name, password))````
````login('HAHA', 'NMNM')  # 打印 ---check admin---   Name:HAHA Pass:NMNM````

4.4 类装饰器

``````class check(object):
``````  def __init__(self, user):
``````    self.user = user
``````
``````  def __call__(self, func):
``````    def wrapper(*args, **kwargs):
``````      if self.user == 'admin':
``````        print('---check admin---')
``````      else:
``````        print('---check other---')
``````      func(*args, **kwargs)
````    return wrapper````
``````@check(user='admin')
``````def login(name, password):
````  print('login name:%s  pass:%s' % (name, password))````
````login('HAHA', 'NMNM')   # 打印 ---check admin---   Name:HAHA Pass:NMNM````