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

Python学习之路:装饰器前奏

时间:2017-11-27 18:46:33      阅读:127      评论:0      收藏:0      [点我收藏+]

标签:turn   int   imp   cal   回收   python学习   time   定义   学习   

装饰器:

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

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

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

 

实现装饰器知识储备:

1、函数即“变量”

2、高阶函数

3、嵌套函数

 

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

import time

def timer(func):
    def warper(*args,**kwargs):
        start_time =time.time()
        func()
        stop_time=time.time()
        print(‘the func run time is %s‘ %(stop_time-start_time))
    return warper

@timer
def test1():
    time.sleep(3)
    print(‘in the test1‘)

test1()

 

匿名函数:不需要起名字(内存回收)

calc = lambda x:x*3
print(calc(3))

 

#函数即“变量”

# def foo():
#     print(‘in the foo‘)
#     bar()
# foo()

#----------------------
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()

 

Python学习之路:装饰器前奏

标签:turn   int   imp   cal   回收   python学习   time   定义   学习   

原文地址:http://www.cnblogs.com/xiaobai005/p/7905312.html

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