python 高阶函数,闭包,函数嵌套 ,装饰器

l = [1, 3]

变成生成器
f1 = list(l.__iter__())
f2 = list(iter(l))

print(f1)
print(f2)

器 函数的意思
装饰 为其它函数添加附加功能
装饰器  本质:函数, 功能:为其它函数添加附加功能

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

import time


def timmer(func):
    def wapper(*args, **kwargs):
        start_time = time.time()
        res = func(*args, **kwargs)
        stop_time = time.time()
        print('函数的执行时间是%s' % (stop_time - start_time))
        return res

    return wapper


@timmer
def cal(l):
    res = 0

    for i in l:
        time.sleep(0.1)
        res += i
    return res


d = cal(range(20))

print(d)

装饰器的知识储备
装饰器 = 高阶函数 + 函数嵌套 + 闭包


高阶参数
1、函数接收的参数是一个函数名
2、函数的返回值是一个函数名
3、满足上述任一条件的 都可以称为高阶函数

import time

def foo():
    print('你好')

def test(func):
    print(func)
    start_time = time.time()
    func()
    stop_time = time.time()
    print(stop_time-start_time)

test(foo)


def foo():
    print('你好')


def test(func):
    return func

foo = test(foo)

foo()


不修改foo源代码
不修改foo调用方式

多运行了一次,不合理  满足不了装饰器

import time

def foo():
    time.sleep(3)
    print('你好')

def timer(func):
    start_time = time.time()
    func()
    stop_time = time.time()
    print(stop_time-start_time)
    return func

foo = timer(foo)

foo()

函数嵌套

def foo():
    print('from foo')
    def test():
        pass


def father(name):
    print('from father %s' %name)
    def son():
        print('from son' %name)
        def grandson():
            print('from grandson' %name)
        grandson()
    son()
    print(locals())

father('林海峰')

闭包  封装变量  包裹


装饰器框架

import time

def timmer(func):
    def wapper():
        start_time = time.time()
        func()  #运行test
        stop_time = time.time()
        print(stop_time-start_time)
    return wapper

@timmer
def test():
    time.sleep(3)
    print('test 函数运行完毕')

test = timmer(test)  # 得到wapper 地址

test() # 执行wapper

语法糖  @timmer  就相当于 test = timmer(test)


函数闭包加上返回值
import time

def timmer(func):
    def wapper():
        start_time = time.time()
        res = func()  #运行test
        stop_time = time.time()
        print(stop_time-start_time)
        return res
    return wapper

@timmer
def test():
    time.sleep(3)
    print('test 函数运行完毕')
    return '返回值'

print(test())


函数闭包加上返回值
import time


def timmer(func):
    def wapper(*args, **kwargs):
        start_time = time.time()
        res = func(*args, **kwargs)  # 运行test
        stop_time = time.time()
        print(stop_time - start_time)
        return res

    return wapper


@timmer
def test(name, age):
    time.sleep(3)
    print('名字%s' %name)
    return '返回值'

@timmer
def test1(gender):
    time.sleep(3)
    print('性别%s' %gender)
    return '返回值'

print(test('sss', 22))
print(test1('male'))

解压序列
a, b, c = (1, 2, 3)

print(a)
print(b)
print(c)

l = (1, 2, 3, 4, 5, 6, 7, 8, 9, 10)

a,*b,c = l

print(a)
print(b)
print(c)

f1 f2 值对换
f1 = 1
f2 = 2
f1, f2 = f2, f1

print(f1)
print(f2)

函数闭包加上认证功能
def auth_func(func):
    def wapper(*args, **kwargs):
        username = input('用户名:').strip()
        password = input('密码:').strip()
        if username == 'sb' and password=='123':
            res = func(*args, **kwargs)
        else:
            print('错误')
        return res
    return wapper

@auth_func
def index():
    print('欢迎来到主页')

@auth_func
def home(name):
    print('欢迎回家%s' % name)

@auth_func
def shopping_car(name):
    print('%s购物车' % name)


index()

home('ki')

shopping_car('ki')

函数闭包模拟session

user_list = [
    {'name': 'alex', 'password': '123'},
    {'name': 'peqi', 'password': '123'},
    {'name': 'yuan', 'password': '123'},
    {'name': 'keng', 'password': '123'}
]

current_dic = {'username': None, 'login': False}


def auth_func(func):
    def wapper(*args, **kwargs):
        if current_dic['username'] and current_dic['login']:
            res = func(*args, **kwargs)
            return res
        username = input('用户名:').strip()
        password = input('密码:').strip()
        for user_dic in user_list:
            if username == user_dic['name'] and password==user_dic['password']:
                current_dic['username'] = username
                current_dic['login'] = True
                res = func(*args, **kwargs)
                return res
        else:
            print('错误')

    return wapper


@auth_func
def index():
    print('欢迎来到主页')


@auth_func
def home(name):
    print('欢迎回家%s' % name)


@auth_func
def shopping_car(name):
    print('%s购物车' % name)


print('before---')
index()

home('小碗')

shopping_car('小碗')



函数闭包带参数的装饰器

user_list = [
    {'name': 'alex', 'password': '123'},
    {'name': 'peqi', 'password': '123'},
    {'name': 'yuan', 'password': '123'},
    {'name': 'keng', 'password': '123'}
]

current_dic = {'username': None, 'login': False}

def auth(auth_type='filedb'):
    def auth_func(func):
        def wapper(*args, **kwargs):
            print(auth_type)
            if auth_type== 'filedb':
                if current_dic['username'] and current_dic['login']:
                    res = func(*args, **kwargs)
                    return res
                username = input('用户名:').strip()
                password = input('密码:').strip()
                for user_dic in user_list:
                    if username == user_dic['name'] and password==user_dic['password']:
                        current_dic['username'] = username
                        current_dic['login'] = True
                        res = func(*args, **kwargs)
                        return res
                else:
                    print('错误')
            else:
                print('其他方式解析')
        return wapper
    return auth_func


@auth(auth_type='filedb')  # auth_func = auth(auth_type='filedb')-->@auth_funs 附加了一个auth_type
def index():
    print('欢迎来到主页')

@auth(auth_type='filedb')
def home(name):
    print('欢迎回家%s' % name)

@auth(auth_type='filedb')
def shopping_car(name):
    print('%s购物车' % name)

print('before---')

index()

home('小碗')

shopping_car('小碗')
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 194,670评论 5 460
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 81,928评论 2 371
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 141,926评论 0 320
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 52,238评论 1 263
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 61,112评论 4 356
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 46,138评论 1 272
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 36,545评论 3 381
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 35,232评论 0 253
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 39,496评论 1 290
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 34,596评论 2 310
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 36,369评论 1 326
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 32,226评论 3 313
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 37,600评论 3 299
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 28,906评论 0 17
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,185评论 1 250
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 41,516评论 2 341
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 40,721评论 2 335

推荐阅读更多精彩内容