python 基础(十四)装饰器

'''
装饰器:
定义:
本质是函数,(装饰其他函数)就是为了给其他函数添加附加功能
原则:
1、不能修改被装饰函数的原代码
2、不能修改被装饰函数的调用方式
实现装饰器的知识储备:
1、函数即‘变量’
x = 1;1在内存中为字符串,通过x找到该值
too():
print("打印函数"); print("打印函数")在内存中为字符串,通过too()找到该值
2、高阶函数
a、把一个函数名当做实参传给另一个函数(在不修改被装饰函数源代码前提下为其添加功能)
b、返回值中包含函数名(不修改函数的调用方式)
3、嵌套函数
装饰器 = (高阶函数 + 嵌套函数)
'''
import  time
def timer(func):     #执行后,func = test1
    def deco(*x,**y):
        start_time = time.time()
        func(*x,**y)    #执行后,func() = test1()
        stop_time = time.time()
        print('执行共用时为%s'%(stop_time - start_time))
    return deco
@timer     #等同于下面的test1 = timer(test1)
def test1():
    time.sleep(3)
    print('in the test1')

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

#test1 = timer(test1)
test1()
test2('Clyde',25)

 进阶版:

import  time
user , passwd = 'Clyde' , '123'
def auth(suth_type):
    print('auth_type:',suth_type)
    def outer_wrapper(func):
        def warppre(*x, **y):
            username = input('username:').strip()
            password = input('password:').strip()
            if user == username and passwd == password:
                print('登录成功')
                res = func(*x, **y)
                print('打印')
                return res
            else:
                exit('验证失败')
        return warppre
    return  outer_wrapper

@auth(suth_type = 'local')
def index():
    print('欢迎进入index页面')
@auth(suth_type = "ldap")
def home():
    print('欢迎进入home页面')
    return 'home返回值'

index()
print(home())
原文地址:https://www.cnblogs.com/zbvc/p/13087107.html