031 Python语法之装饰器

本文深入解析Python装饰器的概念、原理及应用。从装饰器的基本格式到高级使用,包括高阶函数、函数嵌套、通用装饰器及认证装饰器的实现,为读者提供全面的装饰器学习指南。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

装饰器

装饰器格式

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()
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

豆豆orz

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值