python 闭包与装饰器

1、闭包--返回子函数名

作用:使用子函数之外的父函数的变量

闭包就是你调用了一个函数a,这个函数a反悔了一个子函数名b,这个返回的函数b就叫做闭包

代码举例

def a():
    test = 'aa'
    def b():
        print(test)
        return 1
    return b

c = a()
print(c)
print(c())

python 闭包与装饰器

python 闭包与装饰器

 统计做一件事情所需要的时间

python 闭包与装饰器

 做一批事情都想统计时间,如何做  装饰器=闭包+函数式编程

import time

def deco(func):
    def _deco(*args,**kwargs):
        before = time.time()
        ret = func(*args,**kwargs)
        print('cost time : %s' %(time.time() - before))
        return ret
    return _deco

@deco  @装饰器写法
def do_something():
    time.sleep(3)
    print('done')

do_something()

python 闭包与装饰器

装饰器就是把函数(类)包装一下,为函数(类)添加一些附加的功能

装饰器就是一个函数,参数为函数名(类),返回包装后的函数名

装饰就是参数为函数名字的闭包

装饰器 = 闭包 + 函数式编程

#coding:utf-8

def deco(func):
    def _deco():
        print('屌丝: 我有一辆法拉利跑车')
        func()
        print('屌丝: 我北京有一套别墅')
    return _deco

@deco
def confression():
    print('屌丝: 女神 I love you ,will you merry me?')

def accept():
    print('女神: 讨厌,人家愿意了')

confression()
accept()

python 闭包与装饰器

 python 闭包与装饰器

#coding:gbk
import time
def calc_time(func):

    def calc(*args,**kwargs):
        begin_time = time.time()
        ret = func(*args,**kwargs)
        print('huafei time: % second' %(time.time() - begin_time))
    return calc

@calc_time
def eat_bf():
    time.sleep(5)
# t = calc_time(eat_bf)
# t()
eat_bf()

def watch_movie(movie_name):
    print('movie name: %s' % movie_name)
    time.sleep(4)
w = calc_time(watch_movie)
w('gumuliying')

python 闭包与装饰器