011.Python基础--装饰器

装饰器的作用:

针对一段程序,它会实现某个功能

而有的时候,我们想要拓展这个程序的功能:

  此时我们能想到的是在原有程序基础上改动代码,从而实现新增的功能

  再有就是使用装饰器,在不变原程序的基础上,实现新增功能

我们来看一个简单的例子:

import time

def func():

  print('...one...')

  time.sleep(1)

  print('...two...')

func()

此时那我想新增功能:记录一下程序运行了多长时间?

import time

def func():

  start_time = time.time()

  print('...one...')

  time.sleep(1)

  print('...two...')

  end_time = time.time()

  process_time = end_time - start_time

  print('程序运行了:%f' % process_time)

func()

那么装饰器应该怎么写呢?

第一:将程序分开,核心不变的作为一块 ,要装饰的功能作为一块

第二:连接符为   @装饰函数名

第三:装饰部分里面的参数可以自己定义,但是要与执行的保持一致 如:sweet(x)对应x()

tips:装饰器写法又叫糖果语 <>这个名字还真甜~~

import time

#装饰部分,定义一个甜的糖果语 哈哈哈哈

def sweet(x):

  def test():

    start_time = time.time()

    x()

    end_time = time.time()

    process_time = end_time - start_time

    print('程序运行了:%f' % process_time)

  # 返回test函数执行的内容

  return test

@sweet

#核心程序部分

def func():

  print('...one...')

  time.sleep(1)

  print('...two...')

if __name__ == '__main__':

  func()