美文网首页
python装饰器

python装饰器

作者: 奔跑的老少年 | 来源:发表于2018-07-12 17:29 被阅读0次

高阶函数:参数或返回值是函数的函数。
装饰器:通俗来说就是高阶函数+嵌套函数,在工作中我们不能修改线上别人写的代码,假如我们现在需求模块需要用到线上的某个函数,且需要为其增加一些新功能,我们既不能修改原函数内容,也不能修改器调用方式,那么使用装饰器就能解决此问题。

def timer(func):
    def deco():
        func()
        print('deco contains func')
    return deco

@timer
def test1():
    print('this is test1')

test1()

假设已存在test1函数,我们想要给test1打印一条内容'deco contains func',在不改变原test1函数代码、test1调用方式的情况下,我们可以定义一个timer装饰器,timer函数里包含另一个函数deco,且返回deco函数。在deco函数中调用func函数(func是函数,func()是其返回值)并加上新增的功能,最后返回deco函数。在被装饰的函数前面加上‘@装饰函数名’,直接调用test1就执行了新增的功能。执行结果如下:

this is test1
deco contains func

@timer相当于test1 = timer(test1),timer(test1)返回的是一个函数,想要知道期结果还需调用一下test1()

def timer(func):
    def deco():
        func()
        print('deco contains func')
    return deco

# @timer
def test1():
    print('this is test1')

test1 = timer(test1)
test1()

执行结果:

this is test1
deco contains func

当被装饰的函数需要带有参数时,可在deco函数内传入参数:

def timer(func):
    def deco(*args,**kwargs):
        func(*args,**kwargs)
        print('deco contains func')
    return deco

@timer
def test1():
    print('this is test1')

@timer
def test2(*args,**kwargs):
    print('info of %s is %s'% (args[0],kwargs))

test1()
test2('Tim',age = 22,city = 'beijing')

打印结果:

this is test1
deco contains func
info of Tim is {'city': 'beijing', 'age': 22}
deco contains func

args为可变参数,结果包装成一个tulpe返回,*kwargs未关键字参数,结果包装成dic返回。

相关文章

  • 装饰器模式

    介绍 在python装饰器学习 这篇文章中,介绍了python 中的装饰器,python内置了对装饰器的支持。面向...

  • python中的装饰器

    python装饰器详解 Python装饰器学习(九步入门) 装饰器(decorator) 就是一个包装机(wrap...

  • [译] Python装饰器Part II:装饰器参数

    这是Python装饰器讲解的第二部分,上一篇:Python装饰器Part I:装饰器简介 回顾:不带参数的装饰器 ...

  • Python中的装饰器

    Python中的装饰器 不带参数的装饰器 带参数的装饰器 类装饰器 functools.wraps 使用装饰器极大...

  • Python进阶——面向对象

    1. Python中的@property   @property是python自带的装饰器,装饰器(decorat...

  • Python 装饰器填坑指南 | 最常见的报错信息、原因和解决方

    Python 装饰器简介装饰器(Decorator)是 Python 非常实用的一个语法糖功能。装饰器本质是一种返...

  • Python装饰器

    Python装饰器 一、函数装饰器 1.无参装饰器 示例:日志记录装饰器 2.带参装饰器 示例: 二、类装饰器 示例:

  • python3基础---详解装饰器

    1、装饰器原理 2、装饰器语法 3、装饰器执行的时间 装饰器在Python解释器执行的时候,就会进行自动装饰,并不...

  • 2019-05-26python装饰器到底是什么?

    装饰器例子 参考语法 装饰器是什么?个人理解,装饰器,是python中一种写法的定义。他仍然符合python的基本...

  • 2018-07-18

    Python装饰器 装饰,顾名思义,是用来打扮什么东西的。Python装饰...

网友评论

      本文标题:python装饰器

      本文链接:https://www.haomeiwen.com/subject/syzlpftx.html