网络编程
位置:首页>> 网络编程>> Python编程>> python装饰器使用实例详解

python装饰器使用实例详解

作者:Iceberg_710815  发布时间:2021-09-30 15:26: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()

来源:https://www.cnblogs.com/iceberg710815/p/11933039.html

0
投稿

猜你喜欢

手机版 网络编程 asp之家 www.aspxhome.com