最新文章专题视频专题问答1问答10问答100问答1000问答2000关键字专题1关键字专题50关键字专题500关键字专题1500TAG最新视频文章推荐1 推荐3 推荐5 推荐7 推荐9 推荐11 推荐13 推荐15 推荐17 推荐19 推荐21 推荐23 推荐25 推荐27 推荐29 推荐31 推荐33 推荐35 推荐37视频文章20视频文章30视频文章40视频文章50视频文章60 视频文章70视频文章80视频文章90视频文章100视频文章120视频文章140 视频2关键字专题关键字专题tag2tag3文章专题文章专题2文章索引1文章索引2文章索引3文章索引4文章索引5123456789101112131415文章专题3
当前位置: 首页 - 科技 - 知识百科 - 正文

python中的装饰器、生成器与迭代器介绍

来源:动视网 责编:小采 时间:2020-11-27 14:23:40
文档

python中的装饰器、生成器与迭代器介绍

python中的装饰器、生成器与迭代器介绍:装饰器()1、装饰器:本质是函数;装饰器(装饰其他函数),就是为其他函数添加附加功能;原则:1.不能修改被装饰函数的源代码; 2.不能修改被装饰的函数的调用方式;装饰器对被装饰的函数完全透明的,没有修改被装饰函数的代码和调用方式。实现装饰器
推荐度:
导读python中的装饰器、生成器与迭代器介绍:装饰器()1、装饰器:本质是函数;装饰器(装饰其他函数),就是为其他函数添加附加功能;原则:1.不能修改被装饰函数的源代码; 2.不能修改被装饰的函数的调用方式;装饰器对被装饰的函数完全透明的,没有修改被装饰函数的代码和调用方式。实现装饰器


装饰器()

1、装饰器:本质是函数;

装饰器(装饰其他函数),就是为其他函数添加附加功能;

原则:1.不能修改被装饰函数的源代码;

   2.不能修改被装饰的函数的调用方式;

装饰器对被装饰的函数完全透明的,没有修改被装饰函数的代码和调用方式。

实现装饰器知识储备:

1.函数即“变量”;

2.高阶函数;

3.嵌套函数

高阶函数+嵌套函数=》装饰器

匿名函数(lambda表达式)

>>> calc = lambda x:x*3
>>> calc(2)
6

高阶函数:

  a.把一个函数名当做实参传递给另外一个函数;

>>> def bar():  print("in the bar.....")  
>>> def foo(func):
   print(func)>>> foo(bar)
<function bar at 0x7f8b3653cbf8>  


  b.返回值中包含函数名;

>>> import time
>>> def foo():  time.sleep(3)  print("in the foo.....")>>> def main(func):   print(func)   return func>>> t = main(foo)<function foo at 0x7fb7dc9e3378>>>> t()in the foo.....

在不修改源代码的情况下,统计程序运行的时间:

import time

def timmer(func):
def warpper(*args,**kwargs):   #warpper(*args,**kwargs)万能参数,可以指定参数,也可以不指定参数
start_time = time.time() #计算时间
func()
stop_time = time.time()
print("the func run time is %s" %(stop_time-start_time)) #计算函数的运行时间
return warpper

@timmer    #等价于test1 = timmer(test1),因此函数的执行调用是在装饰器里面执行调用的
def test1():
time.sleep(3)
print("in the test1")

test1()
运行结果如下:

in the test1
the func run time is 3.001983404159546

装饰器带参数的情况:

import time

def timmer(func):
def warpper(*args,**kwargs):
start_time = time.time() #计算时间
func(*args,**kwargs)  #执行函数,装饰器参数情况
stop_time = time.time()
print("the func run time is %s" %(stop_time-start_time)) #计算函数的运行时间
return warpper    #返回内层函数名

@timmer
def test1():
time.sleep(3)
print("in the test1")

@timmer    #test2 = timmer(test2)
def test2(name):
print("in the test2 %s" %name)

test1()
test2("alex")
运行结果如下:

in the test1
the func run time is 3.0032410621643066
in the test2 alex
the func run time is 2.3603439331054688e-05

装饰器返回值情况:

import time
user,passwd = "alex","abc123"def auth(func):
 def wrapper(*args,**kwargs):
 username = input("Username:").strip()
 password = input("Password:").strip()if user == username and passwd == password:
 print("