如何理解python装饰器

如何理解装饰器
python 学习遇到的第一个难点是装饰器。装饰器的作用是不大规模改动代码的情况下,增加功能。
作用:为已经存在的对象添加额外的功能
特点:不需要对对象做任何的代码上的变动。
以一个例子来讲装饰器

import time
def timer(func):
  def deco():
    start_time=time.time()
    func()
    stop_time=time.time()
    print("run time is %s"%(stop_time-start_time))
  return deco

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

@timer
def test2():
  time.sleep(3)
  print("in the test2")

test1( )
test2( )


例子是在网上找到的,简单的说就是通过 @timer 对进行了函数进行了改造,在很少的代码量的情况下记录了执行时间。
一般在程序中主要是进行日志记录。

猜你喜欢

转载自www.cnblogs.com/ianxu/p/9083065.html