Python基础 ( 七 ) —— 装饰器

#装饰器

#定义:用于修饰函数的函数(给函数添加新功能)

原则:不改变函数的调用方式

   不改变函数源代码

装饰器=高阶函数(函数的参数或返回值为函数) + 函数嵌套 + 闭包

#小补充

1.获取运行时间

import time
start = time.time()
time.sleep(1)
end = time.time()
print(end-start)

#修饰函数的前身——满足修饰器原则,但多运行了一次原函数

import time
def object():
    time.sleep(1)
    print('对象函数运行成功')
def processor(fuc):
    start_time = time.time()
    fuc()
    end_time = time.time()
    print('函数运行时间:%s' %(end_time-start_time))
    return fuc
object = processor(object)
object()

猜你喜欢

转载自www.cnblogs.com/Matrixssy/p/10305700.html