031 Python语法之装饰器

装饰器

装饰器格式

def costTime(func):
    import time
    startTime = time.time()
    func()
    endTime = time.time()
    print("一共用了", endTime-startTime, "秒")

def func()
    sum1 = 0
    for i in range(1000000):
        sum1+=i

costTime(func)

装饰器

  1. 本质是函数
  2. 功能是用于装饰其他函数,为其他函数附加其它功能

装饰器的原则

  1. 不能修改被装饰器修饰的函数的源代码
  2. 不能修改被装饰器修饰的函数的调用方式

装饰器储备知识

函数即变量

def fun():
    pass

fun是一个变量 

高阶函数

  1. 在不修改被装饰函数源代码的情况下为其添加功能
  2. 返回值中包含函数名

函数嵌套

<!--函数内部定义函数-->
def funA():
    def funB():
        pass
    funB()

funA()

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

进化版装饰器1

import time

def func1():
    time.sleep(3)
    print("func1 run")

def deco(fun):
    start_time = time.time()
    fun()
    end_time = time.time()
    print("run time", end_time - start_time)

deco(func1)

完整版装饰器

import time
def timer(func): #timer(test1)  func=test1
    def deco(*args,**kwargs):   # 这个装饰器是通用的
        start_time=time.time()
        func(*args,**kwargs)   # run test1()
        stop_time = time.time()
        print("the func run time  is %s" %(stop_time-start_time))
    return deco

@timer  #test1=timer(test1)
def test1():
    time.sleep(1)
    print('in the test1')

@timer # test2 = timer(test2)  = deco  test2(name) =deco(name)
def test2(name,age):
    print("test2:",name,age)


test1()
test2("alex",22)

完整版的终极版装饰器

import time
user,passwd = 'alex','abc123'
def auth(auth_type):
    print("auth func:",auth_type)
    def outer_wrapper(func):
        def wrapper(*args, **kwargs):
            print("wrapper func args:", *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)  # from home
                    print("---after authenticaion ")
                    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") # home = wrapper()
def home():
    print("welcome to home  page")
    return "from home"

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

index()
print(home()) #wrapper()
bbs()
发布了151 篇原创文章 · 获赞 26 · 访问量 7万+

猜你喜欢

转载自blog.csdn.net/runnoob_1115/article/details/102822813