首页 > 编程语言 > 详细

python学习笔记(装饰器)

时间:2017-02-23 00:47:20      阅读:208      评论:0      收藏:0      [点我收藏+]

装饰器

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

模拟场景一,在现有的函数中增加某个功能。现有的做法是定义新函数,并且加入函数中。需要修改源代码。

def logger():
    print("logging")

def test1():
    logger()

def test2():
    logger()

场景二,如果是在生产环境中,需要增加功能。不能直接修改源代码。该怎么实现。

原则: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 test1")

test1()

 

实现装饰器知识储备

1. 函数即“变量”

2. 高阶函数

3. 嵌套函数

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

 

通过例子来证明函数即“变量”:

#例一:因为没有定义bar函数,程序报错
def foo():
    print("in the foo")
    bar()
foo()

#例二:程序正常运行,相当于先定义变量x和y,再进行输出。
def bar():
    print("in the bar")
def foo():
    print("in the foo")
    bar()
foo()

#例三:程序正常运行,相当于例二定义变量的顺序相反,但结果不变。
def foo():
    print("in the foo")
    bar()
def bar():
    print("in the bar")
foo()

#例四:程序报错。因为执行foo函数的时候,当顺序执行到bar()语句的时候,这时候bar还没有被定义。
def foo():
    print("in the foo")
    bar()
foo()
def bar():
    print("in the bar")

 

python学习笔记(装饰器)

原文:http://www.cnblogs.com/phenomzh/p/6429593.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!