python

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

2018-05-22  本文已影响0人  little_short
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('小碗')
上一篇下一篇

猜你喜欢

热点阅读