装饰器decorator总结(函数即是变量、高阶函数、嵌套函数、参数组)

装饰器

  1. decorator的本质他就是函数
  2. 原则:--对于被装饰的函数他不发生任何变化,他是透明的。
    • 不能修改被装饰的函数的源代码
    • 不能修改被装饰的函数的调用方式
  3. 函数就是"变量":
    • 普通变量。先定义后使用:如x=1,先定义变量x和再调用变量;函数也如此,先定义函数在调用函数;
python 复制代码
#第一步:定义
def fibo(x):
    if x==0:
        return 1
    elif x==1:
        return 1
    else:
        return fibo(x-1) + fibo(x-2)
#第二步:调用
print(fibo(10))
  • 存储也是一样,函数名以及函数体存储:普通变量x为名牌号,1为值存储在内存中,函数则函数名为名牌号,函数体存储在内存中
  • 匿名函数:特殊的匿名函数没有函数名,用完即回收:lambda x :print(x)
  1. 高阶函数;如def test(x,y,func)
    • 把一个函数当做参数传参给另外一个函数
    • 返回值包含函数名
python 复制代码
def sum(a,b,c):
    return a+b+c

#sum是函数名,为传参
def fun(a,b,c,sum):
    print("count:")
    return sum(a,b,c)  #返回值sum函数名

print(fun(1, 2, 3, sum))
  1. 函数嵌套:定义函数时函数中包含另外一个函数。
python 复制代码
def foo():
    print('in the foo')
    def bar(): #函数foo中的函数
        print('in the bar')
    bar()

foo()
  1. 装饰器=高阶函数+嵌套函数
python 复制代码
def decorator(func):  #func_test01传值给func 高阶函数
    def wrapper(*args,**kwargs):  #嵌套函数 参数组
        start_time = time.time()
        func(*args,**kwargs)  #调用func_test01 参数组
        stop_time = time.time()
        print("the fun runtime is {}".format(stop_time - start_time))
    return wrapper  #返回这个函数的内存地址

@decorator   #func_test01=decorator(func_testo1) 
def fun_test01():  #原函数的源代码不变
    time.sleep(1)
    print('in fun_test01')

fun_test01() #函数调用方式不变
  1. 带参数组的装饰器:三层嵌套
python 复制代码
import time
user_name="agan"
password="123"

def auth(auth_type):
    def outer_wrapper(func):
        print("you auth_type is {}".format(auth_type))
        def wrapper(*args, **kwargs):
            print('wrapper func args:',*args,**kwargs)
            if auth_type == 'local':
                uname = input("Please input your username: ").strip() #去掉字符串开头和结尾的空白字符
                psd = input("Please input your password: ").strip()
                if uname == user_name and psd == password:
                    print("you have authenticated!")
                    res = func(*args, **kwargs)  # 调用func
                    return res
                else:
                    print("wrong username or password!")
            else:
                print("wrong auth type!")
        return wrapper
    return outer_wrapper


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

@auth(auth_type="local") # home = outer_wrapper
def home():
    print("welcome to home page")

index()
home()
相关推荐
zc.z43 分钟前
Context Engineering:深度学习知识点
python·prompt·上下文工程
5G微创业1 小时前
短视频去水印接口怎么对接?一篇讲清 GET 参数、返回字段与多语言示例
python·小程序·api·短视频·去水印
布语world1 小时前
某东pc滑块分析
前端·javascript·网络·python·安全
m0_646429972 小时前
Python pytest 单元测试基础
python
DeepVisionary2 小时前
从1秒多压到0.39秒,Gemini 4 Live靠先应声再干活,把语音延迟降了3倍
python·自动化
Web3&Basketball2 小时前
Playwright实战:27B网页智能体评测3步
python·大模型·浏览器自动化·playwright·网页智能体·评测口径·molmoweb
zc.z2 小时前
RAG (一):从底层原理、Naive RAG 到企业级项目开发与面试实战
人工智能·python·rag
王者鳜錸3 小时前
【中英】-Android离线语音听写-讯飞 AIKit源码实现
开发语言·python·智能手机·安卓·离线中英识别
BK贝壳6 小时前
浮点值也能挂进混合数组:bool-hybrid-array 的 FloatHybridArray 构造、下标与追加本机实测
开发语言·数据结构·python·性能优化·numpy
钱栈up15 小时前
长安汽车把海外年销钉在100万辆,2030年要翻到200万——出海从故事变成基建
爬虫·python·数据分析