Python装饰器的两种使用心得

作者:糖烤栗子& 时间:2023-03-17 17:03:23 

装饰器的基础使用(装饰带参函数)


def decorator(func):
   def inner(info):
       print('inner')
       func(info)
   return inner

@decorator
def show_info(info):
   print(info)

show_info('hello')

防止装饰器改变装饰函数名称

装饰器在装饰函数的时候由于返回的是inner的函数地址,所以函数的名称也会改变 show_info.__name__会变成inner,防止这种现象可以使用functools


import functools

def decorator(func):
@functools.wraps(func)
   def inner(info):
       print('inner')
       func(info)
   return inner

@decorator
def show_info(info):
   print(info)

show_info('hello')

这样写就不会改变被装饰函数的名称

装饰器动态注册函数

此方法在Flask框架的app.Route()的源码中体现


class Commands(object):
   def __init__(self):
       self.cmd = {}

def regist_cmd(self, name: str) -> None:
       def decorator(func):
           self.cmd[name] = func
           print('func:',func)
           return func
       return decorator

commands = Commands()

# 使得s1的值指向show_h的函数地址
@commands.regist_cmd('s1')
def show_h():
   print('show_h')

# 使得s2的值指向show_e的函数地址
@commands.regist_cmd('s2')
def show_e():
   print('show_e')

func = commands.cmd['s1']
func()

个人心得

在阅读装饰器代码时可以使用加(func_name)的方式
以为例


@commands.regist_cmd('s2')
def show_e():
   print('show_e')

即 show_e = commands.regist_cmd('s2')(show_e)

来源:https://www.cnblogs.com/grocerystore/p/15320144.html

标签:Python,装饰器,使用
0
投稿

猜你喜欢

  • [整理版]防止Access数据库被下载的9种方法

    2007-08-10 09:31:00
  • 中文段首不需要空两格

    2010-04-23 20:31:00
  • asp函数InstrRev()介绍及获取文件名例子

    2007-11-19 19:01:00
  • Jsp+Servlet实现简单登录注册查询

    2023-07-15 18:08:08
  • Web UI 设计(网页设计)命名规范

    2009-05-13 13:06:00
  • JSON+JavaScript处理JSON的简单例子

    2023-10-09 09:39:56
  • Python基于Tkinter开发一个爬取B站直播弹幕的工具

    2023-06-21 21:53:12
  • Python爬虫防封ip的一些技巧

    2022-07-02 20:03:44
  • Python中使用ctypes调用C++的方法

    2021-09-28 10:36:13
  • 兼容 IE,Firefox 的图片自动缩放 CSS

    2011-09-27 13:36:58
  • Python的索引与切片原来该这样理解

    2023-11-21 16:17:51
  • 对比国内门户网站对Flash激活限制的处理

    2007-08-23 11:29:00
  • 解析Extjs与php数据交互(增删查改)

    2023-07-19 09:06:42
  • 详解Python编程中time模块的使用

    2023-08-29 16:57:08
  • 用python绘制彩色螺旋线代码

    2023-04-30 15:32:18
  • sql2000如何完美压缩.mdf文件

    2010-03-03 15:47:00
  • JBuilderX+SQL Server开发hibernate

    2023-06-27 00:30:37
  • 为什么视觉设计师需要懂HTML

    2009-06-25 14:16:00
  • NopCommerce架构分析(一)Autofac依赖注入类生成容器

    2023-07-11 21:20:27
  • 在Python反编译中批量pyc转 py的实现代码

    2023-08-11 20:21:04
  • asp之家 网络编程 m.aspxhome.com