Python 装饰器

装饰器:本质仍是函数,用来装饰目标函数的函数。

使用环境:在不改变源代码的前提下,对原函数添加新的功能。

使用原则:1、不改变源代码;

                    2、不改变原函数调用方式;

工作原理:1、将目标函数做为参数传入装饰器(decorator)函数中;

                    2、在装饰器(decorator)函数中,在调用目标函数之前或之后,调用附加功能的函数来装饰目标

                          函数,然后调用目标函数,并返回结果,起到装饰作用。

装饰器函数又分以下几种:

        1、目标函数带参数与不带参数;

import time
# 目标函数不带参数
def decorator(func):
    def wrapper():
        start_time = time.time()
        time.sleep(3)
        func()
        stop_time = time.time()
        print("test run time is %d" % (start_time - stop_time))
    return wrapper

@decorator    # 相当于 test = decorator(test)
def test():
    print("run test")

test()



print("我是分割线".center(40, "*"))


# 目标函数带参数
def decorator1(func):
    def wrapper(*args, **kwargs):
        start_time = time.time()
        time.sleep(5)
        func(*args, **kwargs)
        stop_time = time.time()
        print("test1 run time is %d" % (start_time - stop_time))
    return wrapper

@decorator1    # 相当于 test1 = decorator1(test1)
def test1(name, age=26):
    print("run test1")
    print("%s is %d year old" % (name, age))


test1("Jack")

运行结果:

>>> ================================ RESTART ================================
>>> 
run test
test run time is -3
*****************我是分割线******************
run test1
Jack is 26 year old
test1 run time is -5
*****************我是分割线******************
>>> 


       2、装饰器函数带参数与不带参数;

              对于无参数的装饰器,其装饰器函数的参数是要被装饰的函数对象名;

              对于有参数的装饰器在调用时使用的是应用的参数

对于装饰器带参数,比较迷惑,这里放上参考链接:

http://blog.youkuaiyun.com/dreamcoding/article/details/8611578


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值