yield、生成器、装饰器

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   
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值