Python中的三大神器!装饰器、迭代器、生成器!你精通哪个?

装饰器

Python中的三大神器!装饰器、迭代器、生成器!你精通哪个?

以下示例是一个无参装饰器,为原函数添加了统计运行时间的功能

import time
#定义装饰器
def timer(func):
 def wrapper(*args,**kwargs):
 start_time = time.time()
 res = func(*args,**kwargs)
 stop_time = time.time()
 print("run time is %s" %(sto p_time-start_time))
 return res
 return wrapper 
#调用装饰器
@timer
def index():
 l = []
 for i in range(10000000):
 l.append(i)
#调用阶段
index()

以下是一个有参装饰器,实现简单的认证功能,#数字表示程序依次执行顺序

def auth2(auth_type): #1 #3
 def auth(func): #4 #6
 def wrapper(*args,**kwargs): #7 #10
 if auth_type == 'file': #11
 name=input('username: ')
 password=input('password: ')
 if name == 'zhejiangF4' and password == '666':
 print('auth successfull')
 res=func(*args,**kwargs)
 return res
 else:
 print('auth error')
 elif auth_type == 'sql': #12
 print('nothing!') #13
 return wrapper #8
 return auth #5
 @auth2(auth_type='sql') #2
def index():
 print('welcome to inex page')
 index() #9

迭代器

私信菜鸟007获取相关教程!

Python中的三大神器!装饰器、迭代器、生成器!你精通哪个?

from collections import Iterable,Iterator
s='hello'
l=[1,2,3]
t=(1,2,3)
d={'a':1}
set1={1,2,3,4}
f=open('a.txt')
s.__iter__()
l.__iter__()
t.__iter__()
d.__iter__()
set1.__iter__()
f.__iter__()
print(isinstance(s,Iterable))
print(isinstance(l,Iterable))
print(isinstance(t,Iterable))
print(isinstance(d,Iterable))
print(isinstance(set1,Iterable))
print(isinstance(f,Iterable))
print(isinstance(s,Iterator))
print(isinstance(l,Iterator))
print(isinstance(t,Iterator))
print(isinstance(d,Iterator))
print(isinstance(set1,Iterator))
print(isinstance(f,Iterator))

运行结果如下:

Python中的三大神器!装饰器、迭代器、生成器!你精通哪个?

可以看出,字符串、列表、字典、集合、元组、文件都是可迭代的,但是只有文件是迭代器

生成器

Python中的三大神器!装饰器、迭代器、生成器!你精通哪个?

例1:

from urllib.request import urlopen
def get(url):
 while True:
 def index():
 return urlopen(url).read()
 url = yield index()
g = get('http://www.baidu.com')
next(g)
def run():
 while True:
 url = input("请输入URL:")
 if 'http://' not in url:
 print(g.send('http://'+url))
 else:
 print(g.send(url))
run()

例2:

def cat(filename):
 with open(filename,'r') as f:
 while True:
 line = f.readline()
 if not line:
 break
 else:
 yield line
def grep(string,lines):
 for line in lines:
 if string in line:
 yield line
g1 = cat('a.txt')
g2 = grep('mac',g1)
if __name__ == '__main__':
 m = input("请输入命令:").strip()
 if m == "cat a.txt |grep mac":
 for i in g2:
 print(i)

补充:协程

如果在一个函数内部yield的使用方式是表达式形式的话,如x=yield,那么该函数成为协程函数

直接看例子吧

进群:960410445  即可获取数十天教程!

def hello(func):
 def wrapper(*args,**kwargs):
 res = func(*args,**kwargs)
 next(res)
 return res
 return wrapper
@hello
def eater(name):
 print('%s start to eat food' %name)
 food_list=[]
 while True:
 food=yield food_list
 print('%s get %s ,to start eat' %(name,food))
 food_list.append(food)
 print('done')
e=eater("somebody")
print(e.send('巧克力'))
print(e.send("香蕉"))

猜你喜欢

转载自blog.csdn.net/qq_42156420/article/details/85679746
今日推荐