码迷,mamicode.com
首页 > 编程语言 > 详细

Python装饰器

时间:2017-01-07 21:20:47      阅读:282      评论:0      收藏:0      [点我收藏+]

标签:python 装饰器 迭代器 生成器 高阶函数 嵌套函数

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

原则:1、不能修改被装饰的函数的源代码

    2、不能修改被装饰的函数的调用方式


装饰器对其被装饰的函数是完全透明的

 

基础知识

1、函数即“变量”   定义一个函数相当于就是把函数体赋值给函数名


def test():

    pass

test -->>‘函数体‘


2、高阶函数 

1、把一个函数名当作实参传给另外一个函数(在不修改被装饰函数源代码的情况下为其添加功能) 2、返回值中包含函数名(不修改函数的调用方式)

import  time
def  bar():
    time.sleep(3)
    print(‘in the bar‘)

def test1(func):
    start_time = time.time()
    func()  #run bar
    stop_time = time.time()
    print(‘the fun run time is %s‘ %(stop_time-start_time))


test1(bar)
bar()


技术分享

import  time
def bar():
    time.sleep(3)
    print(‘in the bar‘)


def test2(func):
    print(func)
    return func

test2(bar)

bar = test2(bar)
bar()


技术分享


3、嵌套函数

foo():
    ()
    bar():
        ()
    bar()

foo()


技术分享


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

1、不带参数的装饰器

import time

def timer(func):   #timer(test1)  func=test1

    def deco():
        start_time = time.time()
        func()   #run test1
        stop_time = time.time()
        print(‘the fun run time is %s‘ %(stop_time-start_time))
    return deco

@timer  #test1 = timer(test1)  等同于这个,得到的是deco函数的返回值
def test1():
    time.sleep(3)
    print(‘in the test1‘)


test1()  #--->deco


技术分享


代码执行过程

1、导入模块

2、def timer(func)

3、@timer   自动执行将test1传递给timer函数执行,之后返回deco函数的返回值

4、当执行到test1()函数时候,跳转到deco函数去执行


2、带参数的装饰器

import time

def timer(func):   #timer(test1)  func=test1

    def deco(arg1):
        start_time = time.time()
        func(arg1)   #run test1
        stop_time = time.time()
        print(‘the fun run time is %s‘ %(stop_time-start_time))
    return deco

@timer  #test1 = timer(test1)  等同于这个
def test1(name):
    time.sleep(3)
    print(‘in the test1‘,name)


test1(‘martin‘)  #--->deco(‘martin’)


技术分享

import time

def timer(func):   #timer(test1)  func=test1

    def deco(*args,**kwargs):
        start_time = time.time()
        func(*args,**kwargs)   #run test1
        stop_time = time.time()
        print(‘the fun run time is %s‘ %(stop_time-start_time))
    return deco

@timer  #test1 = timer(test1)  等同于这个
def test1():
    time.sleep(3)
    print(‘in the test1‘)

@timer
def test2(name,age):
    time.sleep(3)
    print(‘in the test2‘,name,age)

#test1 = timer(test1)
print(test1)
test1()  #--->deco
test2(‘martin‘,18)


技术分享

本文出自 “厚德载物” 博客,谢绝转载!

Python装饰器

标签:python 装饰器 迭代器 生成器 高阶函数 嵌套函数

原文地址:http://huaxin.blog.51cto.com/903026/1890045

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!