Python装饰器

#author F

#装饰器: 本质是函数 为其他函数添加功能 文章发表过程->前后添加->运营添加->...
#已经上线 100个函数用到 需要修改
#装饰器原则: 1.不能修改被装饰函数的代码
#           2.不能修改被装饰的函数的调用方式
#也即: 装饰器对被装饰函数是透明的 对被装饰函数完全不影响

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 test 1")


# test1()

#装饰器需要的认识
#1.*函数即变量*  __匿名函数
#2.高阶函数
#   a:把一个函数名当作实参传给另一个函数 (在不修改被装饰函数源代码的情况下为其添加功能)
#   b:返回值中包含函数名 (不修改函数的调用方式)
#3.函数嵌套
#高阶函数+函数嵌套 -> 装饰器
#函数在使用过程中分为两步: 第一是定义 第二是调用


#怎么写一个高阶函数?
# 1.写一个形参
# 2.函数当作实参传入

def bar():
    print("in the bar")


def test2(func):
    print(func)

# test2(bar) #打印函数所在的内存地址

#在返回值中包含函数


def barr():
    time.sleep(1)
    print("in the barr")


def test3(func):
    print(func)  #打印函数的返回地址
    return func  #返回函数的内存地址

# print(test3(barr))  #区别 test3(barr) 和 test3(barr()) 前者传的是函数的地址 后者传递的是函数的返回值
# t = test3(barr)  #返回barr的地址
# t()  #调用地址 运行函数

#嵌套函数
#在函数体内再次定义另一个函数 注意和函数调用的区别
def foo():
    print("in the foo")
    def bara():
        print("in the bar")
#bara() #无法调用 函数的 局部特性
    bara()
foo()
#注意函数的嵌套和函数的调用的区别:
# def test_1():
#     test_2() #这个是函数的调用 不是函数的嵌套
'''

#######################################装饰器########################################
#step1:
# def deco(func):
#     start_time = time.time()
#     func()
#     stop_time = time.time()
#     print("the function cost %s" %(stop_time-start_time))

#step2:
# def deco(func):
#     start_time = time.time()
#     return func
#     stop_time = time.time()
#     print("the function cost %s" %(stop_time-start_time))

#step3
def timer(func):
    def deco():
        start_time = time.time()
        func()
        stop_time = time.time()
        print("the function cost %s" %(stop_time-start_time))
    return deco

@timer
def test1():
    time.sleep(1)
    print('in the test1')
@timer
def test2():
    time.sleep(2)
    print('in the test2')

# test1()
# test2()

#step1: 不修改函数的源代码 添加新功能
# deco(test1)
# deco(test2)

#step2: 不修改函数的调用方式 但没有完成新功能
# test1 = deco(test1)
# test2 = deco(test2)
# test1()
# test2()

#step3: 函数嵌套整合两者
# test1 = timer(test1)
# test2 = timer(test2)
# test1()
# test2()

test1()
test2()

#自我总结: 装饰器其实是把被装饰函数放到一个装饰用的函数中加工处理 然后在这个装饰函数外层包裹一个函数 用来返回这个装饰函数的地址


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值