• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录

白又白i

  • 博客园
  • 联系
  • 订阅
  • 管理

公告

View Post

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

  

 

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

 

 

 

 

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。喜欢的可以关注我的公众号:白又白学Python

 

posted on 2021-08-30 15:03  白又白i  阅读(163)  评论(0)    收藏  举报

刷新页面返回顶部
 
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3