欢迎来到代码驿站!

Python代码

当前位置:首页 > 软件编程 > Python代码

Python带参数的装饰器运行原理解析

时间:2021-02-24 09:40:03|栏目:Python代码|点击:

关于装饰器的理解,特别像《盗梦空间》中的进入梦境和从梦境出来的过程,一层一层的深入梦境,然后又一层一层的返回,被带入梦境的是被装饰的函数,装饰器就是使人入梦的工具。

上代码:

from functools import wraps
def decorator_with_argument(argument=''):
  def outer(func):
    message = argument + func.__name__
    @wraps(func)
    def inner(*args, **kwargs):
      print(message)
      print('This is inner function running')
      return func(*args, **kwargs)
    return inner
  return outer

以上是装饰器的部分。

接下来,是带参数的装饰器:

@decorator_with_argument("Decorator's argument + ")
def pfunc(arg='default'):
  print('This is pfunc running')
  print(f'This " {arg} " is from pfunc argument')

最后,函数的运行:

pfunc("pfunc's argument")

函数本身也是带参数的。输出结果如下:

Decorator's argument + pfunc
This is inner function running
This is pfunc running
This " pfunc's argument " is from pfunc argument

Process finished with exit code 0

下图是关于梦境的具体图示:

上一篇:把JSON数据格式转换为Python的类对象方法详解(两种方法)

栏    目:Python代码

下一篇:python scp 批量同步文件的实现方法

本文标题:Python带参数的装饰器运行原理解析

本文地址:http://www.codeinn.net/misctech/69203.html

推荐教程

广告投放 | 联系我们 | 版权申明

重要申明:本站所有的文章、图片、评论等,均由网友发表或上传并维护或收集自网络,属个人行为,与本站立场无关。

如果侵犯了您的权利,请与我们联系,我们将在24小时内进行处理、任何非本站因素导致的法律后果,本站均不负任何责任。

联系QQ:914707363 | 邮箱:codeinn#126.com(#换成@)

Copyright © 2020 代码驿站 版权所有