装饰器、算法

闭包函数

闭包函数的定义

  闭:在函数的内部定义函数,至少定义两层函数

  包:内部的函数使用外部的函数名称空间中的名字

# 使用场景:闭包函数是第二种传参的方式,一次传参,多次调用

装饰器

装饰器的核心思想:在不改变被装饰对象内部代码和原有的调用方式基础之上在添加额外的功能

统计函数的执行时间

#时间模块
import time
def outer(func):
    def get_time():
    #函数执行之前的时间点
        start_time = time.time
        func()
    #函数执行之后的时间点
        end_time = time.time
        print('函数执行了%秒' % (end_time - start_time))
    return get_time

def index():
    time.sleep(2)
    print('from index')
index = get_time(index)
index()

有参数版本

import time
def outer(func):
    def get_time(*args, **kwargs)
        start_time  = time.time()
        func(*args,**kwargs)
        end_time = time.time
        print('函数执行了%秒' % (end_time - start_time))
    return get_time


def index():
    time.sleep(2)
    print('from index')
index = outer(index)
index()

有返回值版本

import time
def outer(func):
    def get_time(*args, **kwargs):
        start_time = time.time
        func(*args, **kwargs)
        end_time = time.time
        res =end_time -start_time
        return res
    return get_time

def index():
    time.sleep(2)
    print('from index')
index = outer(index)
index()

登录认证功能

def login_auth(func):
    def auth(*args, **kwargs):
        #登录功能
        username = input('username:').strip()
        password = input('password:').strip()
        #判断 用户名和密码是否正确
        if username == 'kevin' and password =='123'
            print('登录成功')
            res = func(*args, **kwargs)
            return res
        else:
            print('用户名或密码错误')
     return auth

@login_auth
def index():
    print('from index')

装饰器的固定模版(语法糖)

def outer(func):
    def inner(*args, **kwargs):
        # 函数执行之前可以添加的功能
        res = func(*args, **kwargs)
        #函数执行之后可以添加的功能
        return res
    return inner

@outer
def index():
    pass
index()

双层语法糖

双重语法糖从下往上走、多重语法糖也是一样的道理,最后都是index = 最上层修饰器(下一层修饰器内部函数) 

def a(func):
    print('a')

    def inner_a(*args, **kwargs):
        print('inner_a')
        res = func(*args, **kwargs)  # 4.inner_b = func  调用inner_b
        return res

    return inner_a


def b(func):
    print('b')

    def inner_b(*args, **kwargs):
        print('inner_b')
        res = func(*args, **kwargs)  # 5.index = func  调用 index
        return res

    return inner_b


@a  # 2. index = a(inner_b)
@b  # 1. inner_b = b(ineer_b)
def index():
    pass


index()  # 3. inner_a = a(inner_b)  调用inner_a

 装饰器修复技术

确保被装饰函数不会因为装饰器带来异常问题

from functools import wraps   # 提出
def a(func):
    print('a')
    @wraps(func)    # 装饰
    def inner_a(*args, **kwargs):
        print('inner_a')
        res = func(*args, **kwargs)
        return res

    return inner_a
@a
def index():
    pass

index()

有参装饰器

def outer(source_data,a,b, *argssss, **kwargsssss):
    # source_data = 'file'
    def login_auth(func):
        def auth(*args, **kwargs):
            # source_data = args[0]
            if source_data == 'file':
                # 来自于文件
            elif source_data == 'mysql':
                # 来自于mysql
            elif source_data == 'oracle':
                # 来自于oracle

            if username =='kevin' and password == '123':
                print('成功')
                func()
            else:
                print('失败')
        return auth
   return login_auth
# @login_auth # index=login_auth(index)
@outer('file'1,2)
def index():
    pass

index('file')

 递归函数

直接或间接调用自己的函数    # 如果递归函数没有结束条件就变成了无限递归,是不允许的

最大默认递归深度:1000

递归分为两个过程:1.递推    2.回溯

递推:一层层往下推

回溯:从最后的结论往回寻找最开始的答案

二分算法

就是将一个列表或(其他容器)里面的数排列组合,将要找里面的数的时候从中间切分比较。丢掉一半,然后再重复,最终至找到或者最后切分为空

x = [11, 2, 3, 44, 55, 66, 77, 88, 99, 100, 23, 34, 45, 56, 67]
x.sort()
def bijiao(l):
    if len(l) == 0:
        print('没有找到这个数。')
        return 123

    zhongjian = len(l)//2
    if s > l[zhongjian]:
        l = l[zhongjian+1:]
        bijiao(l)
    elif s < l[zhongjian]:
        l = l[:zhongjian]
        bijiao(l)
    else:
        print('找到了%s'% s)


s = int(input('请输入你想要比较的数:'))
bijiao(x)

三元表达式

当需求功能出现二选一的时候才会用三元表达式

  语法结构:

  条件成立返回 if 前面的值   if 条件 else 条件不成立返回 else 后面的值

is_beautiful = True
res = '干饭' if 1 > 2 else '学习' if False else '喜欢' if is_beautiful else '不喜欢'

列表生成式

在列表每个元素后面添加内容

lst = ['a', 'b', 'c', 'd']
res = [name + '1' for name in lst]
print(res)  # ['a1', 'b1', 'c1', 'd1']

res1 = [name + '1' for name in lst if name != 'b']
print(res1)   # ['a1', 'c1', 'd1'] if后面不能加else

其他生成式

1.字典

将一个列表字典按照索引生成一个字典

l = [1, 2, 3]
res = {i: j for i, j in enumerate(l)}
print(res)   # {0: 1, 1: 2, 2: 3}

2.集合

将一个列表字典按照索引生成一个集合

l = [1, 2, 3]
res = {i for i in l}
print(res)   # {1, 2, 3}

匿名函数

没有名字的函数,就是只有名字和返回值的简化

一般配合采用的内置函数使用

语法格式:

lambda  形参 :返回值

res = lambda x: x + 1
print(res(2))   # 3
print((lambda x: x + 1)(2))  # 3

常见的内置函数

1.map()(循环)

底层原理就是将容器里的数一个一个传到函数里

def a(x):
    return x + 1


l = [1, 2, 3, 4, 5]

res = map(a, l)
print(res)  # <map object at 0x000001891B2E29D0> 内存地址
print(list(res))  # [2, 3, 4, 5, 6]

2.zip()(拉链)

将多个元素以对应的索引值,组合成一个元组,以最短的元素为最终长度

l = 'hdkcxb'
l1 = [4, 5, 7, 8, 's']
res = zip(l1, l)
print(list(res))  # 需要转变类型,不然会输出内存地址

3.max()(取最大值)

按照ASCII取元素内最大的值

 

4.min()(取最小值)

按照ASCII取元素内最小的值

比较字典的v值返回K:

key = 后面只能加函数

l1 = {'a': 4, 'b': 5, 'c': 7, 's': 8}
print(min(l1, key=lambda key: l1[key]))

5.filter (过滤)

将后面元素里面的一个一个提取出来,然后满足前面函数条件的取出来重新组合

l1 = [11, 33, 44, 5, 66]
print(list(filter(lambda key: key > 30, l1)))    # [33, 44, 66]

 

posted @ 2023-06-05 16:42  Maverick-Lucky  阅读(11)  评论(0)    收藏  举报