Python 闭包函数,装饰器,迭代器,生成器

闭包函数

闭包函数定义:定义在函数内部的函数

特点是:包含对外部作用域而不是对全局作用域名字的引用,该函数就称之为闭包函数

应用领域:延时计算

闭包函数例子:
x=1 def outter(): x=2 def inner(): print(x) return inner #一定要有返回值
f=outter() #赋值给变量,就可在全局调用
######
套结调用 f
=outter() def f1(): x=1000000000 f() #调用上面的函数 f1()

函数体内变量的赋值方式

from urllib.request import urlopen     #导入一个模块

函数体内内部需要一个变量,有两种解决方案
第一种:以参数的形式传入
def get(url):
    return urlopen(url).read()
get('http://www.baidu.com')
get('http://www.baidu.com')
get('http://www.baidu.com')


第二种:包起来
def get(url): #url='http://www.baidu.com'
    # url='http://www.baidu.com'
    def inner():
        return urlopen(url).read()
    return inner

baidu=get('http://www.baidu.com')
print(baidu)
res=baidu()
baidu()
baidu()
baidu()
baidu()

装饰器

 为什么要用装饰器:开放封闭原则,对扩展是开放的,对修改是封闭的        

什么是装饰器
1用来装饰它人,装饰器本身可以是任意可调用对象,被装饰器的对象也可以是任意可调用对象
2遵循的原则:1、不修改被装饰对象的源代码 2、不修改被装饰对象的调用方式
3 目标是:在遵循原则1和2的前提,为被装饰器对象添加上新功能

   

import time

def timmer(func):
    # func=index #最原始的index函数的内存地址
    def inner():
        start_time=time.time()
        func()
        stop_time=time.time()
        print('run time is :[%s]' %(stop_time-start_time))
    return inner

@timmer #index=timmer(index)
def index():
    time.sleep(3)
    print('welcome to index page')


index()

 

无参装饰器例子

import time
from functools import wraps   #想查看属性信息如注释,调用此模块,可当做装饰器使用

def timmer(func):
    @wraps(func)   #将原函数对象的指定属性复制给包装函数对象 也可以使用 index.__doc__ =func.__doc__ 但是wraps功能更多
    def inner(*args,**kwargs):
        start_time=time.time()
        res=func(*args,**kwargs)  #装饰器返回值和参数
        stop_time=time.time()
        print('run time is :[%s]' %(stop_time-start_time))
        #index.__doc__=func.__doc__  上面wraps功能之一
        return res    #返回值

    return inner

@timmer
def index():
    '''
    index function
    :return:
    '''
    time.sleep(3)
    print('welcome to index page')
    return 123

@timmer #home=timmer(home) #home=inner
def home(name):
    time.sleep(2)
    print('welcome %s to home page' %name)
    return 456

# res=index() # res=inner()
# print(res)
#
# res=home('egon') #inner('egon')
# print(res)

# print(index.__doc__)
print(help(index))

 带有认证功能的装饰器,认证成功后保存认证状态,不用重复认证

import time
current_status={'user':None,'login_status':False}


def auth(func):
    def inner(*args,**kwargs):
        if current_status['user'] and current_status['login_status']:
            res = func(*args, **kwargs)
            return res
        name=input('username>>:').strip()
        pwd=input('password>>:').strip()
        if name == 'egon' and pwd == '123':
            print('login successfull')
            current_status['user']=name
            current_status['login_status']=True
            res=func(*args,**kwargs)
            return res
    return inner

@auth #index=auth(index)
def index():
    time.sleep(3)
    print('welcome to index page')
    return 123

@auth
def home(name):
    time.sleep(2)
    print('welcome %s to home page' %name)
    return 456
index()
home('egon')
带有认证功能的装饰器

 

posted @ 2017-09-26 16:01  刘阔  阅读(183)  评论(0编辑  收藏  举报