python之路4:各种器

匿名 (未验证) 提交于 2019-12-02 22:51:30

语法:  

def wrapper(func):     def result():         print('before')         func()         print('after')      return result   @wrapper def foo():     print('foo') 

实例:

#!/usr/bin/env python # -*- coding:utf-8 -*- # __author__ = 'lvlibing'  import time  def timer(func): #timer(test1)  func = test1     def deco(*args,**kwargs):         start_time = time.time()         func(*args,**kwargs) #run test1()         stop_time = time.time()         print('the func run time is %s' %(start_time - stop_time))     return deco  @timer # test1 = timer(test1) def test1():     time.sleep(1)     print('in the test1')  @timer # test2 =timer(test2) = deco test2(name) = deco(name) def test2(name,age):     print('test2:',name,age)  test1() test2('lv',22) 

  

1
2
3
4
5
6
=*forinrange(10)]
>>> L
[0149162536496481]
=*forinrange(10))
>>> g
object0x1022ef630>

#!/usr/bin/env python # -*- coding:utf-8 -*- # __author__ = 'lvlibing'  import time  """ '列表生成式' a = (x * x for x in range(100)) print(a)  for loop in a:     print(loop)      print(a.__next__()) # print(a.__next__()) # print(a.__next__()) """ #Fibonacci斐波那契数列 def fibnaci(max):     n,a,b = 0,0,1     while n < max:         #print(b) #会执行return,获得done返回值         yield b #函数定义中包含yield关键字,此时函数将变成一个生成器,不会执行return     #tuple = (b,a+b)     # a,b = tuple[0],tuple[1]         a,b = b,a+b         n += 1     return 'done'  f=fibnaci(10) print(f) # print(f.__next__()) ''' for n in f:     print(n)      ''' while True:     try:         t = next(f)         print('f:',t)     except StopIteration as e:         print('Generator return value:', e.value)         break  #生产消费者模型,协程(生成器并行运算) def consumer(name):     print('%s准备吃包子了'%name)     while True:         baozhi = yield         print('包子[%s]来了,被[%s]吃了' %(baozhi,name))  def producer(name1,name2):     c1 = consumer(name1)     c2 = consumer(name2)     c1.__next__()     c2.__next__()     print('后厨开始准备做包子')     for i in range(10):         time.sleep(0.01)         print('做了2个包子')         c1.send(i)#send方法调用前面函数yiled         c2.send(i)#send方法调用前面函数yiled  producer('a','b') 

  

#!/usr/bin/env python # -*- coding:utf-8 -*- # __author__ = 'lvlibing'  from collections import Iterable from collections import Iterator  print(isinstance((), Iterable))#T print(isinstance([], Iterable))#T print(isinstance({}, Iterable))#T  print(isinstance({}, Iterator))#F print(isinstance([], Iterator))#F print(isinstance(iter([]), Iterator))#T print(isinstance(iter({}), Iterator))#T  ''' for x in [1,3,5,7,9]:     pass 等同 it = iter([1,3,5,7,9]) while True:     try:         x = next(it)     except StopIteration:         break ''' 

 

http://www.cnblogs.com/alex3714

http://www.cnblogs.com/wupeiqi

internet&python books

PS:如侵权,联我删。

 

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!