In [29]: def getNum(x):
....: y=0
....: while y<x:
....: yield y
....: y+=1
....:
In [30]: g=getNum(10)
In [31]: type(g)
Out[31]: generator
In [32]: g.next()
Out[32]: 0
In [33]: g.next()
Out[33]: 1
……
In [41]: g.next()
Out[41]: 9
In [42]: g.next()
---------------------------------------------------------------------------
StopIteration Traceback (most recent call last)
<ipython-input-42-d7e53364a9a7> in <module>()
----> 1 g.next()
StopIteration:
In [45]: def getNum(x):
y=0
while y<x:
yield y**2
y+=1
In [46]: g = getNum(20)
In [48]: for i in g:
....: print(i)
....:
0
1
4
9
16
25
36
49
64
81
100
121
144
169
196
225
256
289
324
361
装饰器:
本事是一个函数,主要目的是为了装饰其它函数,增强被装饰函数的功能
In [49]: def deco(func):
....: def wrapper():
....: print("begin:")
....: func()
....: print("end")
....: return wrapper
In [52]: @deco
def show():
print("this is the function")
....:
In [53]: show()
begin:
this is the function
end
带参数:
In [54]: def deco(func):
def wrapper(x):
print("begin:")
func(x)
print("end")
return wrapper