首页 > 编程语言 >python装饰器顺序

python装饰器顺序

时间:2023-10-08 16:36:20浏览次数:37  
标签:顺序 python decorator2 Executing def func 装饰 decorator1

Python的装饰器是应用的函数或方法的特殊类型改变,它们会在被装饰的函数或方法被调用时执行。你可以使用多个装饰器来装饰一个函数,装饰器的执行顺序与它们应用的顺序有关

# 使用两个装饰器装饰一个函数
@decorator1
@decorator2
def func():
    pass

在上述代码中,首先应用的装饰器是decorator2,然后应用的装饰器是decorator1。可以这样理解,当你调用func()时,首先执行装饰器 decorator2 对 func 进行装饰,然后执行装饰器 decorator1 对已经被 decorator2 装饰过的 func 进行装饰。

也就是说装饰器的顺序是从下到上(也就是说,最接近函数定义的装饰器最先被应用),或者你可以将其视为从内到外(也就是说,最接近函数定义的装饰器最先被应用)。

下面是一个具体示例,理解装饰器顺序:

def decorator1(func):
    def wrapper():
        print("Executing decorator1")
        func()
    return wrapper

def decorator2(func):
    def wrapper():
        print("Executing decorator2")
        func()
    return wrapper

@decorator1
@decorator2
def hello_world():
    print("Hello, world!")

hello_world()

# 输出:
# Executing decorator1
# Executing decorator2
# Hello, world!

 

 

标签:顺序,python,decorator2,Executing,def,func,装饰,decorator1
From: https://www.cnblogs.com/mlllily/p/17749516.html

相关文章

  • Kubernetes 部署 Python Flask 项目
    1、编写源代码及Dockerfiletest.pyfromflaskimportFlaskimportsocketapp=Flask(__name__)@app.route('/')defhello():returnsocket.gethostbyname(socket.gethostname())if__name__=='__main__':app.run(host='0.0.0.0......
  • python dict和ttl支持自动过期缓存
    pythondict和ttl支持自动过期缓存 github: https://github.com/mailgun/expiringdict 安装pipinstallexpiringdictpipinstallexpiring-dict使用:fromexpiringdictimportExpiringDictfromdatetimeimporttimedelta#创建一个带有过期时间的字典,过期时间......
  • Python-串口通信2
    安装pipinsatllpyserial 初始化简单初始化示例importserialser=serial.Serial('com1',9600,timeout=1) 所有参数 ser=serial.Serial(port=None,#numberofdevice,numberingstartsat#zero.ifeverythingfails,theuser#can......
  • python命令行传参
    #run.pyimportargparseparser=argparse.ArgumentParser()parser.add_argument('--device',type=str,default='cpu:0',help='usewhichdevice')parser.add_argument('--worker',type=int,default=1,help='numofwor......
  • Python学习 —— 初步认知
    写在前面Python是一种流行的高级编程语言,具有简单易学、代码可读性高、应用广泛等优势。它是一种解释型语言,可以直接在终端或集成开发环境(IDE)中运行,而无需事先编译。Python的安装Python的安装过程非常简单。首先,你可以从Python的官方网站(https://www.python.org)下载安装包。根......
  • python查看占用系统内存
    importosimportpsutilinfo=psutil.virtual_memory()print(u'cpu个数:',psutil.cpu_count())print(u'电脑总内存:%.4fGB'%(info.total/1024/1024/1024))print(u'当前进程的内存使用:%.4fGB'%(psutil.Process(os.getpid()).memory_info().rs......
  • Python入门示例系列20 函数
     函数function函数是组织好的,可重复使用的,用来实现单一或相关联功能的代码段。函数能提高应用的模块性,和代码的重复利用率。Python提供了许多内建函数built-in,比如print()。也可以自己创建函数,叫做用户自定义函数。 函数的定义(define)和调用(call)掌握函数的定义和调用。定义一个函......
  • Python入门示例系列18 条件控制 Conditional Statements
    Python提供了bool类型来表示真(对)或假(错),比如常见的5>3比较算式,这个是正确的,在程序世界里称之为真(对),Python使用True来代表;再比如4>20比较算式,这个是错误的,在程序世界里称之为假(错),Python使用False来代表。True和False是Python中的关键字,当作为Python代码输入时,一......
  • Python入门示例系列19 循环语句
    Python中的循环语句有for和while。 while语句Python中while语句的一般形式:while判断条件condition:执行语句statements同样需要注意冒号和缩进。另外,在Python中没有do..while循环。以下实例使用了while来计算1到100的总和:sum=0counter=1whilecounte......
  • Python入门示例系列17 输入与输出( 格式化输出 )
    Python入门示例系列17输入与输出 读取键盘输入(input)Python提供了input()内置函数从标准输入(键盘)读入一行文本,默认的标准输入是键盘。返回结果是字符串。>>>astr=input("请输入:");##input('提示的内容')请输入:123>>>print(astr)123 如果从键盘输入两个数字,并求这......