圣诞节的整理前两周的内容3

一、装饰器:

1.装饰器的基本实现:

 

 

 

 

 

2.

# def cal():
#     res=0
#     for i in range(5,10):
#         res+=i
#     return res
# print(cal())
# # 是从0加到4


#
# import time
# def cal():
#     start_time=time.time()
#     res=0
#     for i in range(10):
#         res+=i
#         stop_time=time.time()
#     print('这个函数的运行时间是%s'%(stop_time-start_time))
#     return res
# print(cal())






# import time
# def timmer(func):
#     def wrapper(*args,**kwargs):
#         start_time=time.time()
#         res=func(*args,**kwargs)
#         stop_time=time.time()
#         print('函数运行的时间是%s'%(stop_time-start_time))
#         return res
#     return wrapper
# @timmer
# def cal():
#     res=0
#     for i in range(10):
#         time.sleep(0.1)
#         res+=i
#     return res
# print(cal())



# 高阶函数复习
# def foo():
#     print('你好啊林师傅')
# def test(func):
#     print(func)
# test(foo())
# test(foo)




# def foo():
#     print('你好啊林师傅')
# def test(func):
#     print(func)
#     func()
# test(foo)




# def foo():
#     print('from the foo')
# def test(func):
#     return func
# print(test(foo))
#
# # pp=test(foo)
# # pp()
#
# foo=test(foo)
# foo()












# def father(name):
#     print('from father %s'%name)
#     def son():
#         print('from the son')
#     print(locals())
# father('alex')


# def foo():
#     name='lijialun'
#     def pp():
#         name='sjdk'
#         print(locals())
#     return pp()
# foo()
# local()函数的作用:将局部变量显示出来,并且以字典的形式。




# 装饰器的基本实现:
import time
def timmer(func):
    def wrapper():
        start_time=time.time()
        func()
        stop_time=time.time()
        print('运行了%s'%(stop_time-start_time))
    return wrapper
@timmer   #相当于   test=timmer(test)
def test():
    time.sleep(3)
    print('test函数运行完毕')
test()






# # 加上返回值
# import time
# def timmer(func):
#     def wrapper():
#         start_time=time.time()
#         res=func()
#         print(res)
#         stop_time=time.time()
#         print('运行了%s'%(stop_time-start_time))
#         return 123
#     return wrapper
# @timmer    #等于test=timmer(test)
# def test():
#     time.sleep(3)
#     print('test函数运行完毕')
#     return '这是test的返回值!'
# # res=test()
# # print(res)
# # # 这时,返回的是none!因为返回的不是test的return,而是timmer的return值,进而返回的是wrapper 的返回值。
# # 而wrapper没有返回值,因此是none
# res=test()
# print(res)







# # 加上参数
# import time
# def timmer(func):
#     def wrapper(*args,**kwargs):
#         start_time=time.time()
#         res=func(*args,**kwargs)
#
#         stop_time=time.time()
#         print('运行了%s'%(stop_time-start_time))
#         return res
#     return wrapper
# @timmer    #等于"test=timmer(test)"
# def test(name,age):
#     time.sleep(1)
#     print('test函数运行完毕',name,age)
#     return '这是test的返回值!'
#
# @timmer   #相当于“test1=timmer(test1)"
# def test1(name,age,gender):
#     time.sleep(1)
#     print('test函数运行完,名字是%s,年龄是%s,性别%s' %(name,age,gender))
#     return '这是test1的返回值!'
# res=test('linhaifeng',18)
# print(res)
# pp=test1('wupeiqi',19,'男')
# print(pp)
# #这样就存在了参数不固定的问题
# #所以不能再wrapper中书写固定的参数——引入*,**







# def test(*args,**kwargs):
#     print(args)
#     print(kwargs)
# test(1,2)
# #输出结果:
# # (1, 2)————元组形式
# # {}————字典形式
# test(1,2,3,name=18)
# #输出结果:
# #  (1, 2, 3)
# # {'name': 18}
# test(1,2,3,name=18,age=1999)
# #输出结果:
# # (1, 2, 3)
# # {'age': 1999, 'name': 18}
# # test(mee=wdw,1,2,3,name=18)
# # SyntaxError: non-keyword arg after keyword arg





# # 分析args,kwargs:
# import time
# def timmer(func):
#     def wrapper(*args,**kwargs):
#         start_time=time.time()
#         res=func(*args,**kwargs)
#
#         stop_time=time.time()
#         print('运行了%s'%(stop_time-start_time))
#         return res
#     return wrapper
# @timmer    #等于"test=timmer(test)"
# def test(name,age):
#     time.sleep(1)
#     print('test函数运行完毕',name,age)
#     return '这是test的返回值!'
#
# @timmer   #相当于“test1=timmer(test1)"
# def test1(name,age,gender):
#     time.sleep(1)
#     print('test函数运行完,名字是%s,年龄是%s,性别%s' %(name,age,gender))
#     return '这是test1的返回值!'
# res=test('linhaifeng',18)
# print(res)
# pp=test1('wupeiqi',19,'男')
# print(pp)
# #这样就存在了参数不固定的问题
# #所以不能再wrapper中书写固定的参数——引入*,**

 

二、装饰器模拟session:

# user_dic={'username':None,'login':False}    #定义了一个全局变量
#
# def auth_func(func):
#     def wrapper(*args,**kwargs):
#         if user_dic['username'] and user_dic['login']:   #字典的索引,即:None and False
#             res = func(*args, **kwargs)
#             return res
#         username=input('用户名:').strip()
#         passwd=input('密码:').strip()
#         if username=='sb' and passwd=='123':
#             user_dic['username']=username
#             user_dic['login']=True      #这两步相当于直接把全局变量给改了,接下来就不用每次都输入用户名和密码了
#             res=func(*args,**kwargs)
#             return res
#         else:
#             print('不对')
#     return wrapper
# @auth_func
# def index():
#     print('欢迎来到京东主页')
# @auth_func
# def home(name):
#     print('%s欢迎回家'%(name))
# @auth_func
# def shopping_car(name):
#     print('%s的购物车里面有【%s】【%s】【%s】'%(name,'奶茶','玩具','小视频'))
# index()
# home('产品经理')
# shopping_car('产品经理')


















user_list=[
    {'name':'alex','passwd':'123'},
    {'name':'linhaifeng','passwd':'123'},
    {'name':'wupeiqi','passwd':'123'},
    {'name':'yuanhao','passwd':'123'}   #用户信息列表
]
current_dic={'username':None,'login':False}    #记录当前用户登录状态

def auth_func(func):
    def wrapper(*args,**kwargs):
        if current_dic['username'] and current_dic['login']:   #字典的索引,即:None and False
            res = func(*args, **kwargs)
            return res
        username=input('用户名:').strip()
        passwd=input('密码:').strip()
        for user_dic in user_list:   #user_dic是新的变量!!
            if username==user_dic['name'] and passwd==user_dic['passwd']:
                current_dic['username']=username
                current_dic['login']=True
                res = func(*args, **kwargs)
                return res
        else:   #注意else 的位置!
            print('用户名不正确,或者密码错误')


    return wrapper
@auth_func
def index():
    print('欢迎来到京东主页')
@auth_func
def home(name):
    print('%s欢迎回家'%(name))
@auth_func
def shopping_car(name):
    print('%s的购物车里面有【%s】【%s】【%s】'%(name,'奶茶','玩具','小视频'))
index()
home('产品经理')
shopping_car('产品经理')

 

三、生成器函数:

# p=(i for i in range(10))
# print(p)
# print(next(p))
# print(next(p))
# print(next(p))
# print(next(p))
# print(next(p))





# def test():
#     print('我要生孩子了')
#     print('我要生孩子了')
#     return '我'
# res=test()
# print((res))

 

四、解压序列:

# a,b,c=[1,2,3]
# print(a)
# print(b)
# print(c)



# a,b,c=(1,2,3,4)
# print(a)
# print(b)
# print(c)
# #报错!




#
# a,b,c='hel'
# print(a)
# print(b)
# print(c)





# # p=[10,3,2,4,6,2,23,53,2,2134]
# #需求:只取第一个和最后一个
# a,*_,c=[10,3,2,4,6,2,23,53,2,2134]
# print(a)
# print(c)

# a,*d,c=[10,3,2,4,6,2,23,53,2,2134]
# print(d)

 

五、加验证:

 

 

 

def auth_func(func):
    def wrapper(*args,**kwargs):
        username=input('用户名:').strip()
        passwd=input('密码:').strip()
        if username=='sb' and passwd=='123':
            res=func(*args,**kwargs)
            return res
        else:
            print('不对')
    return wrapper
@auth_func
def index():
    print('欢迎来到京东主页')
@auth_func
def home(name):
    print('%s欢迎回家'%(name))
@auth_func
def shopping_car(name):
    print('%s的购物车里面有【%s】【%s】【%s】'%(name,'奶茶','玩具','小视频'))
index()
home('产品经理')
shopping_car('产品经理')

六、生产者消费者模型:

#
# # 复习一下enumerate()函数:
# season=['spring','summer','fall','winter']
# print(enumerate(season))
# print(list(enumerate(season)))





#
# # 补充知识:触发生成器有三种方式:1,.__next__()     2.next()    3.send()
# def test():
#     print('开始啦')
#     yield 1
#     print('第一次')
#     yield 2
#     print('第三次')
#     yield 3
# t=test()
#
# # print(t.__next__())
#
# # print(next(t))
#
# # print(t.send(None))
#
# # 以上三个方法的结果是一样的!!!!!
#
# print(t.send(None))
# t.send(None)
# t.send(None)  #相当于None赋值给了yield  !!!
















# def test():
#     print('开始啦')
#     yield
#     print('第一次')
#     yield 2
#     print('第三次')
#     yield 3
# t=test()
# print(t.__next__())
# t.send(None)






#
#
# def test():
#     print('开始啦')
#     first=yield
#     print('第一次',first)
#     yield 2
#     print('第三次')
#     yield 3
# t=test()
# print(t.__next__())
# # # print(t.__next__())
# # print(t.send(None))
# print(t.send('函数停留在first那个位置,我就是给first赋值的'))



# 视频上的讲解:
# def producer():
#     ret=[]
#     for i in range(10000):
#         ret.append('包子%s'%i)
#     return  ret
# def consumer(name):
#     print('我是[%s],我准备开始吃包子了'%name)
#     while True:
#         baozi=yield
#         print('%s  很开心的把[%s]吃掉了' %(name,baozi))
# c1=consumer('wupeiqi')
# c1.__next__()
# c1.send('屎馅包子')






# 自己的思考:
# def consumer(name):
#     print('我是[%s],我准备开始吃包子了'%name)
#
#     baozi=yield
#     print('%s  很开心的把[%s]吃掉了' %(name,baozi))
#     yield 2
# c1=consumer('wupeiqi')
#
# # c1.send('屎馅包子')
# print(c1.__next__())
# c1.send('屎馅包子')






# 终结版:
import time
def consumer(name):
    print('我是%s,我准备开始吃包子了'%name)
    while True:
        baozi=yield
        time.sleep(1)
        print('%s很开心的把【%s】吃掉了'%(name,baozi))
def producuer():
    c1=consumer('wupeiqi')
    c1.__next__()
    for i in range(10):
        time.sleep(1)
        c1.send('包子%s'%i)
producuer()

 

七、函数闭包带参数装饰器:

user_list=[
    {'name':'alex','passwd':'123'},
    {'name':'linhaifeng','passwd':'123'},
    {'name':'wupeiqi','passwd':'123'},
    {'name':'yuanhao','passwd':'123'}   #用户信息列表
]
current_dic={'username':None,'login':False}    #记录当前用户登录状态
def auth(auth_type='filedb'):
    def auth_func(func):   #这时不管auth_func有多少层,都能够接收auth_type这个参数。
        def wrapper(*args,**kwargs):
            if auth_type=='filedb':     #增加if判断auth_type
                if current_dic['username'] and current_dic['login']:   #字典的索引,即:None and False
                    res = func(*args, **kwargs)
                    return res
                username=input('用户名:').strip()
                passwd=input('密码:').strip()
                for user_dic in user_list:   #user_dic是新的变量!!
                    if username==user_dic['name'] and passwd==user_dic['passwd']:
                        current_dic['username']=username
                        current_dic['login']=True
                        res = func(*args, **kwargs)
                        return res
                else:   #注意else 的位置!
                    print('用户名不正确,或者密码错误')
            elif auth_type=='ldap':
                print('鬼知道怎么玩,只是为了多一个选择而已')
            else:
                print('鬼知道你用的是什么类型')
        return wrapper
    return auth_func         #返回auth_func相当于没有做任何改动,只是加了一层可选类型而已 。所以最终还是@auth_func
@auth(auth_type='filedb')
def index():
    print('欢迎来到京东主页')
@auth(auth_type='ldap')
def home(name):
    print('%s欢迎回家'%(name))
@auth(auth_type='xxxxx')
def shopping_car(name):
    print('%s的购物车里面有【%s】【%s】【%s】'%(name,'奶茶','玩具','小视频'))

index()
home('产品经理')
shopping_car('产品经理')

 

posted @ 2018-12-25 16:04  木菲杨  阅读(138)  评论(0编辑  收藏  举报