欢迎来到代码驿站!

Python代码

当前位置:首页 > 软件编程 > Python代码

python装饰器使用实例详解

时间:2021-05-22 08:40:50|栏目:Python代码|点击:

这篇文章主要介绍了python装饰器使用实例详解,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下

python装饰器的作用就是在不想改变原函数代码的情况下,增加新的功能.主要应用了python闭包的概念,现在用1个小例子说明

import time
def foo():
  time.sleep(1)
  
def bar():
  time.sleep(2)
  
def show_time(f):
  def inner():
    start_time = time.time()
    f()
    end_time = time.time()
    print(end_time-start_time)
  return inner
#show_time(f) is a decoration function
foo = show_time(foo)
bar = show_time(bar)

foo()
bar()

上面的代码定义了两个函数foo()和bar(). 通过装饰器函数show_time(f),在其内部定义了另一个闭包函数inner(),再通过foo=show_time(foo),bar=show_time(bar)语句将foo()和bar()函数同装饰器函数关联起来,从而实现了不改变foo()和bar()函数代码,增加打印程序执行时间的功能.程序的执行结果如下:

1.0011370182
2.00142788887

显然,程序在没有改变原函数的情况下,实现了调用原函数显示程序运行时间的功能.

上面的小程序可以将调用装饰器的语句改成@decoration的形式,效果是造价的,改变后的程序如下,其功能和上面的程序完全相同.

import time

@show_time #foo = show_time(foo)
def foo():
  time.sleep(1)
 
@show_time #bar = show_time(bar)
def bar():
  time.sleep(2)
  
  
def show_time(f):
  def inner():
    start_time = time.time()
    f()
    end_time = time.time()
    print(end_time-start_time)
  return inner
#show_time(f) is a decoration function

foo()
bar()

上一篇:python 批量下载bilibili视频的gui程序

栏    目:Python代码

下一篇:TensorFlow 显存使用机制详解

本文标题:python装饰器使用实例详解

本文地址:http://www.codeinn.net/misctech/126456.html

推荐教程

广告投放 | 联系我们 | 版权申明

重要申明:本站所有的文章、图片、评论等,均由网友发表或上传并维护或收集自网络,属个人行为,与本站立场无关。

如果侵犯了您的权利,请与我们联系,我们将在24小时内进行处理、任何非本站因素导致的法律后果,本站均不负任何责任。

联系QQ:914707363 | 邮箱:codeinn#126.com(#换成@)

Copyright © 2020 代码驿站 版权所有