zoukankan      html  css  js  c++  java
  • 装饰器、迭代器、生成器、递归、匿名函数、面向过程编程、三元表达式6

    一.有参装饰器

    def auth(x,engine = "file"):
        def outter(func):
            def wrapper(*args, **kwargs):
                x
                name = input("username>: ").strip()
                pwd = input("password>: ").strip()
    
                if engine == "file":
                    if name == "egon" and pwd == "123":
                        print('login successful'.center(50,'='))
    
                        res = func(*args, **kwargs)
                        return res
                    else:
                        print('username or password error')
                elif engine == "mysql":
                    print("基于mysql的认证")
                elif engine == "ldap":
                    print("基于ldap的认证")
                else:
                    print('engine不存在')
            return wrapper
        return outter
    
    @auth(11,"file")  # @outter函数的内存地址  # index=outter函数的内存地址(index函数的内存地址)
    def index():
        print('from index')
    @auth(11,"mysql")
    def home(name):
        print('welcome %s to home page' %name)
    
    # index=auth(index,"file")
    # home=auth(index,"ldap")
    
    index()
    home("egon")
    
    # 模板
    
    def outter2(x):
        def outter1(func):
            def wrapper(*args, **kwargs):
                res = func(*args, **kwargs)
                return res
    
            return wrapper
        return outter1
    
    
    @outter2(x=1)
    def index():
        pass

    二.叠加多个装饰器

    # def deco1(func1):  # func1 = wrapper2的内存地址
    #     def wrapper1(*args, **kwargs):
    #         print('====>wrapper1')
    #         res1 = func1(*args, **kwargs)
    #         return res1
    #     return wrapper1
    #
    # def deco2(func2):  # func2 = wrapper3的内存地址
    #     def wrapper2(*args, **kwargs):
    #         print('====>wrapper2')
    #         res2 = func2(*args, **kwargs)
    #         return res2
    #     return wrapper2
    #
    # def deco3(func3):  # func3 = index函数的内存地址
    #     def wrapper3(*args, **kwargs):
    #         print('====>wrapper3')
    #         res3 = func3(*args, **kwargs)
    #         return res3
    #     return wrapper3
    #
    # # 加载/得到wrapper函数的顺序是自下而上的
    # # 我们运行wrapper函数的顺序是:
    #
    #         # index=wrapper1的内存地址
    # @deco1  # deco1(wrapper2的内存地址) => wrapper1的内存地址
    # @deco2  # deco2(wrapper3的内存地址) => wrapper2的内存地址
    # @deco3  # deco3(index函数的内存地址) => wrapper3的内存地址
    # def index():
    #     print('from index')
    #
    # # print(index)
    # res=index()
    # """
    # ====>wrapper1
    # ====>wrapper2
    # ====>wrapper3
    # from index
    # """
    import time
    
    def timmer(func):
        def wrapper(*args,**kwargs):
            start=time.time()
            res=func(*args,**kwargs)
            stop=time.time()
            print("run time is : %s" %(stop - start))
            return res
        return wrapper  # 千万不要加括号
    
    def auth(x,engine = "file"):
        def outter(func):
            def wrapper(*args, **kwargs):
                x
                name = input("username>: ").strip()
                pwd = input("password>: ").strip()
    
                if engine == "file":
                    if name == "egon" and pwd == "123":
                        print('login successful'.center(50,'='))
    
                        res = func(*args, **kwargs)
                        return res
                    else:
                        print('username or password error')
                elif engine == "mysql":
                    print("基于mysql的认证")
                elif engine == "ldap":
                    print("基于ldap的认证")
                else:
                    print('engine不存在')
            return wrapper
        return outter
    
    @auth(111,"file")
    @timmer
    def index():
        print("index=====>")
        time.sleep(3)
    
    index()

    三.迭代器

    """
    1 什么是迭代器
        器=>工具
        迭代:迭代是一个重复的过程,但是每次重复都是基于上一次的结果而来的
            count =  1
            while count < 5:
                print(count)
                count+=1
    
        迭代器:迭代取值的工具
    
    2 为何要用迭代器
        优点:
            1、迭代器是一种通用的、不依赖于索引的迭代取值方式
            2、节省内存
    
        缺点:
            1、取值不灵活,只能往后取,不能取指定的值
            2、无法预知长度,只能取一次
    
    3 如何用迭代器
        python为一些类型内置了__iter__方法,调用了__iter__方法就会将原类型转换成一个迭代器
    
        可迭代对象:内置有__iter__
        迭代器对象:内置有__next__,__iter__
    
    
    """
    
    # 例1
    # names=["egon","alex","lxx"]
    # names="abcdefg"
    
    # i=0
    # while i < len(names):
    #     print(names[i])
    #     i+=1
    
    # 例2:
    # c="hello"
    # d=["a",'B','C']
    # e=("a",'B','C')
    # a={"k1":111}
    # g={111,222,333}
    # f=open("a.txt",'w')
    
    # dic={'k1':111,"k2":222,'k3':333}
    # dic={111,222,333}
    # iter_dic=dic.__iter__()
    
    # print(iter_dic.__iter__() is iter_dic)
    # print(iter_dic)
    
    # res=iter_dic.__next__()
    # print(res)
    #
    # res=iter_dic.__next__()
    # print(res)
    #
    # res=iter_dic.__next__()
    # print(res)
    #
    # res=iter_dic.__next__()
    # print(res)
    
    dic={111,222,333}
    iter_dic=dic.__iter__()
    
    while True:
        try:
            print(iter_dic.__next__())
        except StopIteration:
            break
    print('='*50)
    iter_dic=dic.__iter__()
    while True:
        try:
            print(iter_dic.__next__())
        except StopIteration:
            break
    
    # for循环的底层工作原理
    # 1、dic.__iter__()拿到一个迭代器
    # 2、k=迭代器.__next__(),循环往复直到抛出异常
    # 3、for循环会捕捉异常,然后结束循环
    
    
    # dic = {'k1': 111, "k2": 222, 'k3': 333}
    # # for k in dic:
    # #     print(k,dic[k])
    # # print('='*50)
    # # for k in dic:
    # #     print(k,dic[k])
    
    # for k in f:
    #     print(k)

    四.生成器

    # 生成器:自定义的迭代器
    # 函数内但凡出现yield关键字,再调用函数,不会触发函数体代码的运行
    # 会得到一个返回值,该返回值就是一个生成器对象,也就是自定义的迭代器
    
    # yield与return
    # 相同点:都能返回值
    # 不同点:yield能返回多次值,而return只能返回一次值函数就立即结束
    def func():
        print("first")
        yield
        print("second")
        yield 222
        return 777777777777777777
        print("third")
        yield 333
        print('fourth')
    
    g=func()
    # print(g)
    # iter(g)  # g.__iter__()
    # next(g)  # g.p__next__()
    
    # res=next(g)
    # print(res)
    #
    # res=next(g)
    # print(res)
    #
    # res=next(g)
    # print(res)
    #
    # next(g)
    
    
    #range(1,5,2)
    def my_range(start,stop,step=1):
        while start < stop:
            yield start
            start += step
    
    
    for i in my_range(1,5,2):
        print(i)

    五.递归

    # 递归调用:在调用一个函数的过程中又直接或者间接地调用函数自己
    # 例1:
    # def foo():
    #     print('from foo')
    #     foo()
    
    # foo()
    
    # import sys
    # print(sys.getrecursionlimit())
    # sys.setrecursionlimit(2000)
    
    # 例2:
    # def foo():
    #     print('from foo')
    #     bar()
    #
    # def bar():
    #     print('from bar')
    #     foo()
    #
    # foo()
    
    # 递归调用有两个阶段
    # 1、回溯:一层一层地递归调用下去
    # 2、递推:在某一层结束递归调用,开始向上一层一层地返回
    
    # age(5) = age(4) + 10
    # age(4) = age(3) + 10
    # age(3) = age(2) + 10
    # age(2) = age(1) + 10
    # age(1) = 18
    
    #n = 1: age(1) = 18
    #n > 1: age(n) = age(n-1) + 10
    
    # def age(n):
    #     if n == 1:
    #         return 18
    #     return age(n-1) + 10
    #
    # res=age(5)
    # print(res)
    
    # 应用示例1:
    # nums=[1,[2,[3,[4,[5,[6,[7,[8,[9]]]]]]]]]
    #
    # def func(list1):
    #     for item in list1:
    #         if type(item) is list:
    #             func(item)
    #         else:
    #             print(item)
    #
    # func(nums)
    
    # 应用示例2:二分法
    nums=[-3,11,13,25,37,39,43,52,77,84,91]
    
    def search(list1,find_num):
        print(list1)
        if len(list1) == 0:
            print('not exists')
            return
    
        mid_index = len(list1) // 2
        if find_num > list1[mid_index]:
            # on the right
            search(list1[mid_index+1:],find_num)
        elif find_num < list1[mid_index]:
            # on the left
            search(list1[:mid_index],find_num)
        else:
            print('find it')
    
    search(nums,85)

    六.匿名函数

    # 匿名函数:没有名字的函数,意味着只能调用一次就被回收了
    # 应用场景:临时调用一次的场景
    
    
    # res=(lambda x,y:x+y)(1,2)
    # print(res)
    
    # 匿名函数应用示例
    salaries = {
        "egon": 3000,
        "alex": 5000,
        "zhangsan": 1000,
    }
    
    # def func(k):
    #     return salaries[k]
    
    # res = max(salaries,key=lambda k:salaries[k])
    # print(res)
    
    # print(max([11,10,44,9]))
    
    # res = min(salaries,key=lambda k:salaries[k])
    # print(res)
    
    # res=sorted([11,10,44,9],reverse=True)
    # print(res)
    
    # res=sorted(salaries,key=lambda k:salaries[k],reverse=True)
    # print(res)
    
    # 了解
    # map
    # filter
    # reduce

    七.面向过程编程

    '''
    面向过程编程
        核心是过程二字,过程即做事的步骤,即先干什么、再干什么、然后干什么...
        基于该思想写程序就好比是在设计一条条的流水线
    
    优点:复杂问题流程化、进而简单化
    缺点:扩展性差
    
    '''

    八.三元表达式

    def max2(x,y):
        if x > y:
            return x
        else:
            return y
    
    # res =条件成立时运行的表达式 if 条件 else 条件不成立时运行的表达式
    x=11
    y=22
    
    res=x*12 if x > y else y*100
    print(res)

    九.生成器

    # l=[]
    # for i in range(1,6):
    #     if i > 3:
    #         l.append(i)
    #
    # print(l)
    #1、列表生成式
    # res=[i for i in range(1,6) if i > 3]
    # print(res)
    
    #2、集合生成式
    # res={i for i in range(1,6) if i > 3}
    # print(res,type(res))
    
    #3、字典生成式
    # items=[("name","egon"),('age',18),('gender','male')]
    # dict(items)
    # res={k:v for k,v in items if k != "age"}
    # print(res,type(res))
    
    #4、生成器表达式
    # res = (i for i in range(1, 6) if i > 3)
    # print(res)
    
    # print(next(res))
    # print(next(res))
    # print(next(res))
    
    # def my_sum(nums,res=0):
    #     for num in nums:
    #         res+=num
    #     return res
    
    
    # with open(r'D:weekend_s7day062 叠加多个装饰器.py',mode='rt',encoding="utf-8") as f:
    #     # print(len(f.read()))  # 2061
    #
    #     # res=0
    #     # for line in f:
    #     #     res+=len(line)
    #
    #     res=sum(len(line) for line in f)
    #     print(res)
    #
    #
    #     # g=(len(line) for line in f)
    #     # res=my_sum(g)
    #
    #     # print(res)
    
    
    # 了解:map、filter、reduce
    # 1、map函数
    # salaries=[1000,2000,3000,4000,5000]
    # res=map(lambda num:num*12,salaries)
    # print(res)
    # print(list(res))
    
    # print((num*12 for num in salaries))
    
    #2、filter函数
    # names=['egon',"alex_dsb","liuqingzheng_dsb"]
    # res=filter(lambda n:n.endswith("dsb"),names)
    # print(res)
    
    # print([name for name in names if name.endswith('dsb')])
    
    #3、reduce函数
    # from functools import reduce
    #
    # res=reduce(lambda x,y:x+y,[1,2],100)
    # print(res)
  • 相关阅读:
    【费用流】【CODEVS】1227 方格取数2
    【CODEVS】1034 家园
    【BZOJ】1066: [SCOI2007]蜥蜴
    【最大流】【CODEVS】1993 草地排水
    【HDU】2191 多重背包问题
    【TYVJ】1520 树的直径
    【BZOJ】1984 月下“毛景树”
    【BZOJ】1588: [HNOI2002]营业额统计
    【NOI】2004 郁闷的出纳员
    【POJ】2892 Tunnel Warfare
  • 原文地址:https://www.cnblogs.com/2722127842qq-123/p/13470824.html
Copyright © 2011-2022 走看看