python装饰器

python装饰器

一、装饰器简介

装饰器的存在是为了适用两个场景,一个是增强被装饰函数的行为,另一个是代码重用。装饰器的本质是函数,其参数是另一个函数(被装饰的函数)。装饰器通常会额外处理被装饰的函数,然后把它返回,或者将其替换成另一个函数或可调用对象。

定义:装饰器本质是函数,装饰器就是为其他函数添加附加功能。

原则:不能修改被装饰函数的代码,不能修改被装饰函数的调用方式

装饰器 = 高阶函数 + 嵌套函数

二、高阶函数

高阶函数满足如下两个条件中的任意一个:a.可以接受函数名作为实参;b.返回值中可以包含函数名。

import time

def bar():
    time.sleep(3);
    print("in the bar");

def test1(func):
    start_time = time.time();
    func();
    stop_time = time.time();
    print("the func run times %s" %(stop_time - start_time));

test1(bar)

三、嵌套函数

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

    bar();

foo()

四、装饰器实现

 
import time
def timer(func):
    def deco(*args,**kwargs):
        start_time = time.time();
        func(*args,**kwargs);
        stop_time = time.time();
        print("the func run times %s" % (stop_time - start_time));
    return deco;

@timer
def test1():
    time.sleep(3);
    print("in the bar");

@timer
def test2(name,age):
    print("the name is %s"%(name))
    print("the age is %s"%(age))

test1()
test2("zzhaokai",23)



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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值