python_详解装饰器

# Author : XueFeng
# 定义:本质是函数,,(装饰其他函数),就是为其他函数添加附加功能
# 原则:   1.不能修改被装饰函数的源代码
#          2.不能修改被装饰函数的调用方式
# 实现装饰器知识储备:
# 1.函数即’变量‘
# 2.高阶函数
# 3.嵌套函数
# 高阶函数+嵌套函数=》装饰器
def logger():
    print('logging')
def test1():
    pass
    logger()
def test2():
    pass
    logger()
test1()
test2()

import time
def timmer(func):
    def warpper(*args, **kwargs):
        start_time = time.time()
        func()
        stop_time = time.time()
        print('the func run time is %s' % (stop_time - start_time))
    return warpper
@timmer
def test1():
    time.sleep(3)
    print('in the test1')
test1()

# 这里解释的是函数即变量的意思
# 调用函数放在最后面,定义函数位置可以交换     
# 相当于:
# x=2                 y=3
# y=3                 x=2
# print(x,y)          print(x,y)
def f1():
    f2()
    return 0
def f2():
    print('this is the test')
f1()

# 这里对高阶函数进行重新解释
# a. 传递实参
def test1(func):
    print(func)
    func()
def bar():
    print('jim is me')
test1(bar)

# b.传递返回值
import time
def timmer1(func):
    start_time = time.time()
    func()
    stop_time = time.time()
    print('the func run time is %s' % (stop_time - start_time))
    return func  # 返回函数func地址
def bar():
    time.sleep(3)
    print('bar')

t = timmer1(bar)  # 把函数体func的地址传给t
t()  # 用t替代bar指向函数体

# 嵌套函数
x=0
def nam():
    x=1
    def nam1():
        x = 2
        def nam2():
            x = 3
            print(x)
        nam2()
    nam1()
nam()           # 就近原则
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值