python函数——装饰器

python函数——装饰器

1、装饰器前奏

1.1需求:

chao(pm):hankin(人名)啊!写一个名为beHandsome的函数。
hankin(coder):写完了,如下!
def beHandsome():
    print('i will be handsome')

1.2需求变更

chao(pm):hankin(人名)啊!统计一下beHandsome函数执行时间。
hankin(coder):写完了,如下!
import time
def beHandsome():
    startTime = time.time()
    print('i will be handsome')
    print(time.time() - startTime )

beHandsome()

1.3需求再变更

chao(pm):hankin(人名)啊!把以前写的那几个函数都统计一下执行了多长时间。
hankin(coder):写完了,如下!
import time
def caculateTime(func):
    startTime = time.time()
    func()
    print(time.time() - startTime )

def beHandsome():
    print('i will be handsome')

caculateTime(beHandsome)  # 若干个函数就作为参数传递给caculateTime()

2、装饰器开始

2.1优化1.3代码

import time

def beHandsome():
    print('i will be handsome')

def caculateTime(func):
    def inner():             # 定义内部函数
        startTime = time.time()
        func()
        print(time.time() - startTime )
    return inner            # 返回内部函数

beHandsome = caculateTime(beHandsome) 
beHandsome()
# 装饰器初具规模,唯一不完美是还要在做一次赋值调用

2.2再优化

import time
def caculateTime(func):
    def inner():
        startTime = time.time()
        func()
        print(time.time() - startTime)
    return inner

@caculateTime   # 等价于  beHandsome= caculateTime(beHandsome) 
def beHandsome():
    print('i will be handsome')

beHandsome()

2.3总结

  • 装饰器的本质:一个闭包函数
  • 装饰器的功能:在不修改原函数及其调用方式的情况下对原函数功能进行扩展

3、高潮

3.1带参装饰器

import time
def caculateTime(func):
    def inner(name):  # 单个参数
        startTime = time.time()
        func(name)    # 单个参数
        print(time.time() - startTime)
    return inner

@caculateTime   # 等价于  beHandsome = caculateTime(beHandsome) 
def beHandsome(name):   # 单个参数
    print('%s will be handsome'%name)


beHandsome("hankin") # 单个参数

3.2带多个参且有返回值装饰器

import time
def caculateTime(func):
    def inner(*args,**kwargs):  # 多个参数
        startTime = time.time()
        ret = func(*args,**kwargs) # 多个参数
        print(time.time() - startTime)
        return ret
    return inner

@caculateTime   
def beHandsome(name):  
    print('%s will be handsome'%name)

@caculateTime   
def beHandsomeMan(name,sex):
    print('%s will be a handsome %s'%(name,sex))
    return 'done'

beHandsome('hankin')
print(beHandsomeMan('hankin','man'))

4、结尾

4.1装饰器的一般结构

def caculateTime(func):
    def inner(*args,**kwargs):
        '''执行函数之前要做的'''
        ret = func(*args,**kwargs)
        '''执行函数之后要做的'''
        return ret
    return inner
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值