python学习笔记-装饰器

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

原则:
1、不能修改被装饰的函数的源代码
2、不能修改被装饰的函数的调用方式

实现装饰器的知识储备:

1、函数既变量

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

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

foo()

输出:
in the foo
in the bar

2、高阶函数
a:把一个函数名当做实参传给另一个函数。(不修改被装饰的函数代码,为其增加新的功能)

import 
timedef bar():    
  time.sleep(1)    
  print("in the bar")

def test1(func):    
  start_time = time.time()    
  func()    
  end_time = time.time()   
  print("use time is %s" % (end_time - start_time))

test1(bar)

输出:
in the bar
use time is 1.0030739307403564

b:返回值中包含函数名。(不修改函数的调用方式)

import time
def bar():    
  time.sleep(3)    
  print("in the bar")
def test(func):    
  print(func)   
  return funca = test(bar)

a()

输出:
<function bar at 0x108347048>
in the bar

3、嵌套函数

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

foo()

输出:
in the foo
in the bar

通过高阶函数+嵌套函数 实现 装饰器

import time

def timer(func):
    def bar(*args, **kwargs):
        start_time = time.time()
        func(*args, **kwargs)
        end_time = time.time()
        print("the func run time is %s" % (end_time-start_time))
    return bar

@timer
def test1():
    time.sleep(1)
    print("in the test1")

@timer
def test2(name):
    time.sleep(2)
    print("in the test2 %s" % name)


test1()
test2("alex")

输出:
in the test1
the func run time is 1.0011811256408691
in the test2 alex
the func run time is 2.0028319358825684
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 要点: 函数式编程:注意不是“函数编程”,多了一个“式” 模块:如何使用模块 面向对象编程:面向对象的概念、属性、...
    victorsungo阅读 1,636评论 0 6
  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 174,613评论 25 709
  • Python进阶框架 希望大家喜欢,点赞哦首先感谢廖雪峰老师对于该课程的讲解 一、函数式编程 1.1 函数式编程简...
    Gaolex阅读 5,592评论 6 53
  • 炎炎夏日,昏昏欲睡,能让人眼前一亮的就是游泳了,在河边长大的我,最快乐的事,就是和朋友们一起整天泡在河里,清晨出门...
    花生zfh阅读 225评论 1 0
  • 考试体会: 2016年12月10日,我参加了BIM一级等级考试。卷子总体难度不大,大部分的题目还是比较基础的。下面...
    wuhao1993阅读 8,779评论 10 14