python面试题 ———— 装饰器是什么,有什么功能,能用在什么业务场景?

概念

  1装饰器的实现是由闭包支撑的
  2装饰器本质上是一个 python函数,它可以在让其他函数在不需要做任何代码的变动的前提下增加额外的功能
  3装饰器的返回值也是一个函数的对象,它经常用于有切面需求的场景,实现路由传参,fask的路由传参依赖于装饰器,浏览器通过ur访问到装饰器的路由,从而访问视图函数获得返回的HTML页面

应用场景

  1.可以在外层函数加上时间计算函数,计算函数运行时间
  2.计算函数运行次数;
  3.可以用在框架的路由传参上
  4.插入日志,作为函数的运行日志;
  5.事务处理,可以让函数实现事务的一致性,让函数要么一起运行成功,要么一起运行失败
  6.缓存,实现缓存处理
  7.权限的校验,在函数外层套上权限校验的代码,实现权限校验

1、手写普通装饰器

#!/usr/bin/python
# -*- coding: utf-8 -*-
def outer_wrapper(func):
    def wrapper(*args, **kwargs):
        print('---->')
        res = func(*args, **kwargs)
    return wrapper

@outer_wrapper
def home():
    print("welcome to home  page")
    return "from home"

home()

2、三级装饰器

#!/usr/bin/python
# -*- coding: utf-8 -*-
def auth(auth_type):
    def outer_wrapper(func):
        def wrapper(*args, **kwargs):
            print("---->", auth_type)
            res = func(*args, **kwargs)
        return wrapper
    return outer_wrapper

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

home()

3、计算函数执行时间装饰器

#! /usr/bin/env pythonf
# -*- coding: utf-8 -*-
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("running time is %s"%(stop_time-start_time))
    return deco
@timer     # test1=timer(test1)
def test1():
    time.sleep(3)
    print("in the test1")
test1()

装饰器,生成器,迭代器详解:https://blog.csdn.net/weixin_46451496/article/details/104614115

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

hsw Come on

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

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

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

打赏作者

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

抵扣说明:

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

余额充值