天天看点

装饰器_python

一、装饰器中提及的知识点

装饰器主要作用:在原函数基础上添加新功能

1、作用域:LEGB

2、高阶函数

3、闭包(在一个内部函数中,对在外部作用域(但不是在全局作用域)的变量进行引用,那么内部函数就认为是闭包)

闭包只是用于解释现象

#闭包例子:
def outer():
    x=10
    def inner(): #inner是一个内部函数
        print(x)  #引用外部变量
    return inner  #结论:内部函数inner就是一个闭包
outer()()      

装饰器函数例子1:给函数添加计算执行时间的功能

import time
def show_time(fun): #需添加功能函数(这里是添加打印执行时间)
    def inner():
        start=time.time()
        time.sleep(2)
        fun()
        stop=time.time()
        print(stop-start)
    return inner
def foo(): #原函数
    print('f0000')
foo=show_time(foo)  #重新指定函数加入新功能,并沿用原函数名
foo()      

也可以使用新的调用方法:在原函数前面添加@show_time

import time
def show_time(fun): #需添加功能函数(这里是添加打印执行时间)
    def inner():
        start=time.time()
        time.sleep(2)
        fun()
        stop=time.time()
        print(stop-start)
    return inner

@show_time  #装饰器添加show_time部分功能,这是规定写法,省略后面的foo=show_time(foo)
def foo(): #原函数
    print('f0000')
foo()      

例子2:继续优化为不定项的装饰器

import time
def show_time(fun): #需添加功能函数(这里是添加打印执行时间)
    def inner(*args,**kwargs):
        start=time.time()
        time.sleep(2)
        fun(*args,**kwargs)
        stop=time.time()
        print(stop-start)
    return inner

@show_time  #装饰器添加show_time部分功能,这是规定写法,省略后面的foo=show_time(foo)
def foo(n): #原函数
    print(n*n)
foo(3)

装饰器用途:如检验有无登录