• linkedu视频
  • 平面设计
  • 电脑入门
  • 操作系统
  • 办公应用
  • 电脑硬件
  • 动画设计
  • 3D设计
  • 网页设计
  • CAD设计
  • 影音处理
  • 数据库
  • 程序设计
  • 认证考试
  • 信息管理
  • 信息安全
菜单
linkedu.com
  • 网页制作
  • 数据库
  • 程序设计
  • 操作系统
  • CMS教程
  • 游戏攻略
  • 脚本语言
  • 平面设计
  • 软件教程
  • 网络安全
  • 电脑知识
  • 服务器
  • 视频教程
  • vbs
  • DOS/BAT
  • hta/htc
  • python
  • perl
  • VBA
  • ColdFusion
  • ruby
  • PowerShell
  • Lua
  • Golang
  • linux shell
您的位置:首页 > 脚本语言 >python > python装饰器decorator介绍

python装饰器decorator介绍

作者:junjie 字体:[增加 减小] 来源:互联网

junjie 通过本文主要向大家介绍了python decorator,decorator,decorator是什么意思,decorator模式,interior decorator等相关知识,希望对您有所帮助,也希望大家支持linkedu.com www.linkedu.com

一、装饰器decorator

decorator设计模式允许动态地对现有的对象或函数包装以至于修改现有的职责和行为,简单地讲用来动态地扩展现有的功能。其实也就是其他语言中的AOP的概念,将对象或函数的真正功能也其他辅助的功能的分离。

二、Python中的decorator

python中的decorator通常为输入一个函数,经过装饰后返回另一个函数。  比较常用的功能一般使用decorator来实现,例如python自带的staticmethod和classmethod。

装饰器有两种形式:
@A
def foo():
    pass
</div>

相当于:
def foo():
    pass
foo = A(foo)
</div>

第二种为带参数的:
@A(arg)
def foo():
    pass
</div>

则相当于:
def foo():
    pass
foo = A(arg)(foo)
</div>

可以看出第一种的装饰器是个返回函数的函数,第二种的装饰器是个返回函数的函数的函数。

python中的decorator可以多个同时使用,如下:

@A
@B
@C
def f (): pass
   
# it is same as below
def f(): pass
f = A(B(C(f)))
</div>

三、Python中常用的decorator实例

decorator通常用来在执行前进行权限认证,日志记录,甚至修改传入参数,或者在执行后对返回结果进行预处理,甚至可以截断函数的执行等等。

实例1:

from functools import wraps
def logged(func):
    @wraps(func)
    def with_logging(*args, **kwargs):
        print (func.__name__() + " was called")
        return func(*args, **kwargs)
    return with_logging

@logged
def f(x):
   """does some math"""
   return x + x * x

print (f.__name__)  # prints 'f'
print (f.__doc__)   # prints 'does some math'
</div>

注意functools.wraps()函数的作用:调用经过装饰的函数,相当于调用一个新函数,那查看函数参数,注释,甚至函数名的时候,就只能看到装饰器的相关信息,被包装函数的信息被丢掉了。而wraps则可以帮你转移这些信息,参见http://stackoverflow.com/questions/308999/what-does-functools-wraps-do

</div>

您可能想查找下面的文章:

  • 分析Python中设计模式之Decorator装饰器模式的要点
  • python装饰器decorator介绍
  • python装饰器decorator介绍
  • Python装饰器decorator用法实例
  • python self,cls,decorator的理解

相关文章

  • Python中os和shutil模块实用方法集锦
  • python使用内存zipfile对象在内存中打包文件示例
  • php使用递归与迭代实现快速排序示例
  • python之yield表达式学习
  • 利用Python的Django框架生成PDF文件的教程
  • 跟老齐学Python之赋值,简单也不简单
  • Python中MySQLdb和torndb模块对MySQL的断连问题处理
  • 详解Python的Django框架中Manager方法的使用
  • 举例讲解Python的Tornado框架实现数据可视化的教程
  • ubuntu系统下 python链接mysql数据库的方法

文章分类

  • vbs
  • DOS/BAT
  • hta/htc
  • python
  • perl
  • VBA
  • ColdFusion
  • ruby
  • PowerShell
  • Lua
  • Golang
  • linux shell

最近更新的内容

    • Python每天必学之bytes字节
    • CentOS下使用yum安装python-pip失败的完美解决方法
    • python入门之语句(if语句、while语句、for语句)
    • Python中绑定与未绑定的类方法用法分析
    • 详解Django框架中的视图级缓存
    • 简单介绍Python中的几种数据类型
    • Pycharm学习教程(2) 代码风格
    • 下载给定网页上图片的方法
    • 使用Python的PEAK来适配协议的教程
    • 为Python的web框架编写前端模版的教程

关于我们 - 联系我们 - 免责声明 - 网站地图

©2020-2025 All Rights Reserved. linkedu.com 版权所有