python学习,day4:装饰器的使用示例

---恢复内容开始---

装饰器:本质是函数,(装饰其他函数)就是为其他函数添加附加功能

装饰器有其独特的原则:1、不能修改被装饰的函数的源代码

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

例子

import time
def timmer(func):  #装饰器
    def warpper(*args,**kwargs):
        start_time = time.time()
        func()
        stop_time =time.time()
        print('the func run time is %s' %(stop_time - start_time))
    return warpper

@timmer

def test():   #被修饰函数
    time.sleep(3)
    print('in the test')


test()

实现装饰器只是储备:

1、函数即“变量”

2、阶段函数

a.把一个函数当做实参传给另外一个函数(在不修改被装饰函数源代码的情况下为其添加功能)

import time
def bar():
    time.sleep(3)
    print('in the bar')
def test(func):
    time_start = time.time()
    func()
    time_stop = time.time()
    print('running time is %s'%(time_stop-time_start))

test(bar)

b。返回值中包含函数名(不修改函数的调用方式)

def test2(func):
    print(func)
    return func
#print(test2(bar))

bar = test2(bar)
bar()

3、嵌套函数

x=0
def granda():
    x=1
    def dad():
        x=2
        def son():
            x=3
            print(x)
        son()     #必须有,要运行才能生效,否则会跳过
    dad()
granda()

高洁函数+嵌套函数 =》装饰器

 装饰器使用

# coding=utf-8
# Author: RyAn Bi
import time

def timer(func):   #timer(test1)   func = test1
    def deco():
        start_time = time.time()
        func()   #run  test1
        stop_time = time.time()
        print('the func running time is %s'%(stop_time-start_time))
    return deco
@timer    #等同于 test1 = timer(test1)  调用装饰器
def test1():
    time.sleep(2)
    print('in the test1')
@timer    #等同于 test2 = timer(test2)   调用装饰器
def test2():
    time.sleep(2)
    print('in the test2')

# t = timer(test1)    #t 获得了deco的地址,地址存的是deco运行的结果
# t()    #调出结果

test1()
test2()
原文地址:https://www.cnblogs.com/bbgoal/p/10432006.html