1.迭代器
可迭代对象:
list, str, tuple etc. ——>for … in … 遍历——>遍历(迭代)
迭代器协议:对象必须提供一个next方法,执行该方法要么返回迭代中的下一项,要么引起StopIt eration异常,以终止迭代(只能往下走,不能回退)
实现了迭代器协议的对象就是可迭代对象
如何实现
li = [1, 2, 3]
li_iter = li.__iter__() # 等于iter(li)
print(li_iter.__next__())
print(li_iter.__next__())
print(li_iter.__next__())
>>>1
>>>2
>>>3
可迭代对象测试
使用isstance()来判断一个对象是否可迭代
collections模块
from collections import Iterable #使用isstance()来判断一个对象是否可迭代
print(isinstance([], Iterable))
>>>True
自定义一个类,其可以容纳数据
from collections import Iterable
class Myclass:
def __init__(self):
self.names = []
def add(self, name):
self.names.append(name)
my_class = Myclass()
my_class.add('Tom')
my_class.add('Jack')
print('是否为可迭代对象', isinstance(my_class,Iterable))
for i in my_class:
print(i)
>>>是否为可迭代对象 True
>>>Traceback (most recent call last):<__main__.Myclass object at 0x0000016E7C701208>
>>> File "D:/python.shixun/day11.py", line 39, in <module>
>>> for i in my_class:
>>>TypeError: 'Myclass' object is not iterable
回顾之前说的__iter__方法,可以为我们提供一个迭代器
在迭代一个可迭代对象的时候,实际上 就是获取该对象提供的一个迭代器。然后通过该迭代器依次获取对象的每一个数据。
from collections import Iterable
class Myclass:
def __init__(self):
self.names = []
def add(self, name):
self.names.append(name)
def __iter__(self):
return self.names.__iter__()
my_class = Myclass()
my_class.add('Tom')
my_class.add('Jack')
for i in my_class:
print(i)
>>>Tom
>>>Jack
通过迭代器迭代
my_class_iter = iter(my_class)
print(my_class_iter)
print(next(my_class_iter))
print(next(my_class_iter))
print(next(my_class_iter))
for… in …循环的本质
就是通过iter()函数获取可迭代对象的Iterable的迭代器,然后对获取到的迭代器不断调用next()方法来获取下一个值并将其复制item,当遇到StopIteration的异常后,退出。
class test:
def __init__(self, data=1):
self.data = data
def __iter__(self):
return self
def __next__(self):
if self.data > 5:
raise StopIteration
else:
self.data += 1
return self.data
for i in test(2):
print(i)
>>>3
>>>4
>>>5
>>>6
应用场景
迭代器的核心就是通过next()函数调用返回下一个数据值。如果每次返回的数据组不是在一个已有的数据集合中读取的,而是通过程序按照一定规律计算生成。那么就意味着可以不用以来一个已有的数据集合,nameIy。
无需将所有的迭代数据一次性缓存下来供后续使用,这样可以节省大量的储存(内存)空间。
demo:
斐波拉契数列
现在我们希望通过for … in … 的方式来遍历斐波拉契数列中的前n个数。0.
class FibIterator(object):
"""斐波拉契数列迭代器"""
def __init__(self, n):
"""记录生成的个数"""
self.n = n
"""记录当前记录的索引"""
self.current_index = 0
"""记录两个初始值"""
self.num1 = 0
self.num2 = 1
def __next__(self):
if self.current_index < self.n:
num = self.num1
self.num1, self.num2 = self.num2, self.num1+self.num2
self.current_index += 1
return num
else:
raise StopIteration
def __iter__(self):
return self
fib = FibIterator(10)
for num in fib:
print(num)
2.生成器
生成器,利用迭代器,我们可以在每次迭代获取数据时(通过next()方法)按照特定的规律进行生成。但是我们在实现一个迭代器时,关于当前迭代的状态需要我们自己记录,进而才能根据当前的状态生成下一个数据。为了达到记录当前状态,并配合next()函数进行迭代使用,可以采用更简便的语法。
即生成器(generator),生成器是一种特殊的迭代器,它比迭代器更优雅。
创建一个生成器
列表[]——>()
li = [x**2 for x in range(6)]
print(li)
gen = (x**2 for x in range(6))
print(gen)
print("通过next()函数取得下一个值")
print(next(gen))
print(next(gen))
# print(next(gen))
# print(next(gen))
# print(next(gen))
# print(next(gen))
for i in gen:
print(i, end=' ')
>>>[0, 1, 4, 9, 16, 25]
>>><generator object <genexpr> at 0x000001C0F0F24EB8>
>>>通过next()函数取得下一个值
>>>0
>>>1
>>>4 9 16 25
2.1生成器函数
在函数中如果出现了yield关键字,那么该函数就不再是一个普通函数而是一个生成器函数。
demo:
def foo():
yield 1
yield 2
return #return后面如果有语句,为异常参数
yield 3
f = foo()
print(next(f)) #程序会停留在对应yield后的语句
print(next(f))
print(next(f)) #当程序遇到return,return后的语句不会再执行,因此报错
>>>1
>>>2
>>> File "D:/python.shixun/day11.py", line 112, in <module>
>>> print(next(f))
>>>StopIteration
next和yield进行匹配。如果遇到return,return后的语句不会再执行,直接抛出StopIteration,中止迭代。
在一个生成器中,如果return后又返回值,那么这个值就是异常的说明,而不是返回值。
def odd():
n = 1
while True:
yield n
n += 2
odd_num = odd()
print(next(odd_num))
print(next(odd_num))
print(next(odd_num))
>>>1
>>>3
>>>5
for i in range(0,6):
print(next(odd_num))
>>>7
>>>9
>>>11
>>>13
>>>
通过类手动编写迭代器,实现类似的效果。
class OddIter:
def __init__(self):
self.start = -1
def __iter__(self):
return self
def __next__(self):
self.start += 2
return self.start
odd = OddIter()
for i in range(6):
print(next(odd))
>>>1
>>>3
>>>5
>>>7
>>>9
>>>11
生成器生成的方法
Help on generator object:
odd = class generator(object)
| Methods defined here:
|
| __del__(...)
|
| __getattribute__(self, name, /)
| Return getattr(self, name).
|
| __iter__(self, /)
| Implement iter(self).
|
| __next__(self, /)
| Implement next(self).
|
| __repr__(self, /)
| Return repr(self).
|
| close(...)
| close() -> raise GeneratorExit inside generator.
|
| send(...)
| send(arg) -> send 'arg' into generator,
| return next yielded value or raise StopIteration.
|
| throw(...)
| throw(typ[,val[,tb]]) -> raise exception in generator,
| return next yielded value or raise StopIteration.
|
| ----------------------------------------------------------------------
| Data descriptors defined here:
|
| gi_code
|
| gi_frame
|
| gi_running
|
| gi_yieldfrom
| object being iterated by yield from, or None
None
- close()
- 手动关闭生成器函数,后面调用会
def gen():
yield 1
yield 2
yield 3
yield 4
g = gen()
print(next(g))
print(next(g))
g.close()
print(next(g))
>>>1
>>>Traceback (most recent call last):
>>>2
>>> File "D:/python.shixun/day11.py", line 148, in <module>
>>> print(next(g))
>>>StopIteration
- send
- x = yield y #send()的作用就是使x赋值为其传送的值(send的参数),然后让生成器执行到i下一个yield
- 如果生成器未启动,则必须在使用send()前启动生成器,启动的方法可以是gen.next(),也可以是gen.send(None)执行到第一个yield处。之后就可以使用send(para)不断地传入值了
- 如果已启动,则send(para)的作用就是给x赋值为已发送的值(send的参数),然后让生成器执行到下一个yield
def gen():
value = 0
while True:
receive = yield value
if receive == 'e':
break
value = 'got:%s'%receive
g = gen()
print(g.send(None))
print(g.send('aaa'))
print(g.throw(Exception, "补充"))
- throw
- 手动抛出异常
3.闭包
什么是闭包
闭是封闭(函数中的函数),包是包含(该内部函数对外部函数作用域而非全局作用域变量的引用)
闭包:
- 内部函数对外部函数作用域里的变量的引用
- 函数内的属性,都是有生命周期,都是在函数执行期间
- 闭包内的闭包函数私有化了变量,完成了数据的封装,类似面向对象
def foo():
print("in foo()")
def bar():
print("in bar")
1.直接运行内部函数报错
bar()
2.考虑先运行外部函数,再运行内部函数,依然会报错
foo()
bar()
由于作用域的问题,函数内的熟属性,都是有生命周期的,只有在函数执行期间
再考虑这段代码,只有调用foo()时,内部的print()及bar()才能存活。
现在我们为了让foo()内的bar()存活,就是调用bar(),该怎么做?
把bar()函数返回给函数
def foo():
print("in foo()")
def bar():
print("in bar()")
return bar
var = foo()
var()
>>print("in bar()")
前面说,内部函数对外部函数作用于变量的引用,如果是变量呢?
li = [1, 2, 3, 4, 5]
def foo(obj):
print("foo:", obj)
def bar():
obj[0] += 1
print("bar", obj)
return bar
var = foo(li)
var()
var()
>>>foo: [1, 2, 3, 4, 5]
>>>bar [2, 2, 3, 4, 5]
>>>bar [3, 2, 3, 4, 5]
4.装饰器
首先,看一个demo:
@func1
def func():
print("aaa")
装饰器存在的意义
- 不影响原有函数的功能
- 可以添加新功能
一般常见的,比如拿到第三方的API接口,第三方不允许修改这个接口。这个时候用到装饰器。
装饰器本身也是函数,作用是为现有存在的函数,在函数不改变的基础上,增加一些功能进行装饰。
它是以闭包的形式去实现的。
在使用装饰器函数时,在被装饰的函数的前一行,使用@装饰器函数名
形式来进行装饰。
现在在一个项目中,有很多函数,由于我们的项目越来越大,功能越来越多,导致程序越来越慢。
其中一个功能函数的功能,实现一百万次的累加
def my_count():
s = 0
for i in range(10000001):
s += 1
print("sum:", s)
start = time.time()
my_count()
end = time.time()
print("执行时间为:", (end-start))
成功的实现时间计算。但如果有很多函数每个函数写一遍不现实。
所以用一个函数实现
import time
def my_count():
s = 0
for i in range(10000001):
s += 1
print("sum:", s)
def count_time(func):
start = time.time()
func()
end = time.time()
print("执行时间为:", (end-start))
count_time(my_count)
>>>sum: 10000001
>>>执行时间为: 0.5003633499145508
经过修改后,定义一个函数来实现时间计算功能。
初看上去,比之前好很多。在使用时将对应的函数传入到时间计算函数中。
但仍然影响了原来的使用。
def count_time(func):
def wrapper():
start = time.time()
func()
end = time.time()
print("执行时间为:", (end - start))
return wrapper
@count_time
def my_count():
s = 0
for i in range(10000001):
s += 1
print("sum:", s)
my_count()
>>>sum: 10000001
>>>执行时间为: 0.5003633499145508
在使用时,让my_count函数重新指向count_time函数返回的函数引用。这样使用my_count时,就和原来的使用方式一样了
这也是新的好处,定义闭包函数后,只需要通过@装饰器函数名
形式的装饰器语法,就可以将@装饰器函数名
加到要装饰的函数前即可。
这种不改变原有函数功能,对函数进行拓展的形式,就成为装饰器。
再执行@装饰器函数名
时,就是将原函数传递到闭包中。然后,原函数的引用指向闭包返回的装饰过的内部函数的引用。