一、装饰器

1、器:代表函数,装饰器本质是函数,(装饰器他函数)

2、功能:为其他函数添加附加功能

3、原则:

  (1)不能修改被装饰函数的源代码

  (2)不能修改被装饰函数的调用方式

4、实现装饰器知识储备:

  (1)函数即“变量”,定义变量就是把函数体赋值给函数名(函数引用基数内存回收)

  (2)高阶函数

    a、把一个函数名当作实参传给另一个函数

    b、返回值中包含函数名

   其中a不修改源代码,b不修改调用方式

  (3)嵌套函数

    在函数体内去声明一个函数(def)

#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Author  : Willpower-chen
# @blog: http://www.cnblogs.com/willpower-chen/
#
# import time
'''
装饰器本质是函数,函数即‘变量’
'''

# #例子1
# def foo():
#     time.sleep(3)
#     print('in the foo')
#     bar()
#
# foo()


# #例子2
# def bar():
#     print('in the bar')
# def foo():
#     time.sleep(3)
#     print('in the foo')
#     bar()
# foo()
#
#
# #例子3
# def foo():
#     time.sleep(3)
#     print('in the foo')
#     bar()
# def bar():
#     print('in the bar')
# foo()
#
# #例子4
# def foo():
#     time.sleep(3)
#     print('in the foo')
#     bar()
# foo()
# def bar():
#     print('in the bar')





import time

def timer(func):
    def recod(*args,**kwargs):
        start_time = time.time()
        func(*args,**kwargs)
        stop_time = time.time()
        run_time = stop_time - start_time
        print('调用%s 耗时 %s'%(func,run_time))
    return recod
@timer
def test1():
    time.sleep(3)
    print('in the test1')

@timer
def test2(name,age,sex):
    time.sleep(3)
    print('yourname is: ',name,age,sex)

test1()
test2('cjk','23','man')
View Code

相关文章:

  • 2022-12-23
  • 2022-12-23
  • 2021-08-23
  • 2021-11-23
  • 2022-12-23
  • 2021-08-13
  • 2022-12-23
  • 2022-12-23
猜你喜欢
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
相关资源
相似解决方案