python的装饰器

作者: 两分与桥 | 来源:发表于2018-03-21 21:38 被阅读10次

装饰器

# 装饰器,特性,注解
# 对修改是封闭的,对扩展是开发的
import time

def print_current_time(func):
    print(time.time())
    func()

def f1():
    print('This is a function-1')

def f2():
    print('This is a function-2')

print_current_time(f1)
print_current_time(f2)

#输出结果
#1521624272.8735173
#This is a function-1
#1521624272.992277
#This is a function-2

不修改函数调用方式,依旧可以修改输出

# 对修改是封闭的,对扩展是开发的
import time

def decorator(func):
    def wrapper():
        print(time.time())
        func()
    return wrapper

@decorator
def f1():
    print('This is a function-1')
def f2():
    print('This is a function-2')

f1()
f2()

#输出结果
#1521637627.8076153
#This is a function-1
#This is a function-2

利用 *args 可以传入任意个参数

# 对修改是封闭的,对扩展是开发的
import time

def decorator(func):
    def wrapper(*args):
        print(time.time())
        func(*args)
    return wrapper

@decorator
def f0():
    print('This is a function-0 ')

@decorator
def f1(func_name):
    print('This is a function-1 ' + func_name)

@decorator
def f2(func_name1, func_name2):
    print('This is a function-2 ' + func_name1)
    print('This is a function-2 ' + func_name2)

f0()
f1('test')
f2('try', 'try')

#输出结果
#1521639444.4680157
#This is a function-0
#1521639444.4700003
#This is a function-1 test
#1521639444.4730039
#This is a function-2 try
#This is a function-2 try

装饰器的最终形态,**kw 代表关键字参数,多余的关键字会被当作字典打印出来

def decorator(func):
    def wrapper(*args, **kw):
        print(time.time())
        func(*args, **kw)
    return wrapper

不破坏代码实现,实现代码复用性,可以多个装饰器堆叠使用

相关文章

  • 装饰器模式

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

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

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

  • Python中的装饰器

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

  • Python进阶——面向对象

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

  • python中的装饰器

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

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

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

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

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

  • Python装饰器

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

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

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

  • 2018-07-18

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

网友评论

    本文标题:python的装饰器

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