python装饰器

一、装饰器如何理解?

1.先来理解两个词"器","装饰"

"":器在这里我们可以理解为函数。

"装饰":可以理解为添加、附加的意思。

2.装饰器的定义:

装饰器它的本质是函数,装饰其他函数就是为其他函数添加附加功能。

3.装饰器的原则:

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

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

二、装饰器的初步使用

1.需求:给原有的函数test添加一个打印函数执行时间日志的装饰器timmer。

def test():
    time.sleep(3)
    print('in the test')

test1()

2.代码实现

__author__ = 'coco'

import time

def timmer(func):
    def warpper(*args,**kwargs):
        start_time = time.time()
        func(*args,**kwargs)
        stop_time=time.time()
        print('the func tun time is %s' % (stop_time - start_time))
    return warpper

@timmer
def test1():
    time.sleep(3)
    print('in the test1')

@timmer
def test2(name,age):
time.sleep(1)
   print('test2:',name,age) test1()
test2("coco",22)

三、总结

实现装饰期知识储备:
1.函数即“变量”
2.高阶函数
  a.把一个函数名当作实参传递给另外一个函数(在不修改被装饰函数源代码的情况下为其添加功能)
  b.返回值中包含函数名(不修改函数的调用方式)
3.嵌套函数

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

四、高级版装饰器示例

__author__ = 'coco'

import time

user,passwd = 'coco','123456'

def auth(auth_type):
    print("auth func:",auth_type)
    def outer_wrapper(func):
            def wrapper(*args,**kwargs):
                print("wrapper auth func:",*args,**kwargs)
                if auth_type == 'local':
                    username = input("Username:").strip()
                    password = input("Password:").strip()

                    if user == username and passwd == password:
                        print("\033[32;1mUser has passed authentication\033[0m")
                        res = func(*args,**kwargs)
                        return res
                    else:
                        exit("\033[31;1mInvalid username or password\033[0m")
                elif auth_type == 'ldap':
                    print("ldap验证")
            return wrapper
    return outer_wrapper

def index():
    print("welcome to index page")

@auth(auth_type="local")
def home():
    print("welcome to home page")
    return "from home"

@auth(auth_type="ldap")
def bbs():
    print("welcome to bbs page")

index()
print(home())
bbs()
原文地址:https://www.cnblogs.com/share100/p/6810842.html