• day18


    1、编写课上讲解的有参装饰器准备明天默写

    from functools import wraps
    def auth(db_type):
        @wraps
      	def deco(func):
            def wrapper(*args, **kwargs):
            		name = input('请输入用户名:').strip()
                password= input('请输入密码:').strip()
                if db_type == 'file':
                  	print('基于文件的验证!')
                    if name == 'egon' and password == '123':
              					res = func(*args, **kwargs)
                        return res
                elif db_type == 'mysql':
                  	print('基于 mysql 的验证')
                elif db_type == 'ldap':
                  	print('基于 ldap 的验证')
                else:
                  	print('不支持该db_type')
            return wrapper
        return deco
              
    @auth('file')
    def index(x,y):
      	print('index-->%s,%s'%(x,y))
        
    @auth('mysql')
    def home(name):
      	print('home-->%s'%name)
        
    @auth('ldap')
    def transfer():
      	print('transfer')
        
    index(1,2)
    home('egon')
    transfer()
    
    
    结果展示:
    index-->1,2
    home-->egon
    transfer
    

    2:还记得我们用函数对象的概念,制作一个函数字典的操作吗,来来来,我们有更高大上的做法,在文件开头声明一个空字典,然后在每个函数前加上装饰器,完成自动添加到字典的操作

    func_dic = {}
    count = 0
    def outter(func):
        def wrapper(*args, **kwargs):
            global count
            count += 1
            res = func(*args, **kwargs)
            if func.__name__ not in func_dic.values():
                func_dic[f'{count}'] = func.__name__
    
            return res
        return wrapper
    
    @outter
    def login():
        print('login...')
    
    
    @outter
    def check_balance():
        print('check_balance...')
    
    
    @outter
    def withdraw():
        print('withdraw...')
    
    login()
    check_balance()
    withdraw()
    login()
    print(func_dic)
    

    3、 编写日志装饰器,实现功能如:一旦函数f1执行,则将消息2017-07-21 11:12:11 f1 run写入到日志文件中,日志文件路径可以指定
    注意:时间格式的获取
    import time
    time.strftime('%Y-%m-%d %X')

    import time
    from functools import wraps
    
    def tail_log(path):
        def outter(func):
            @wraps(func)
            def wrapper(*args, **kwargs):
                current_time = time.strftime('%Y-%m-%d %X')
                with open(path, 'a', encoding='utf-8')as f:
                    f.write(f'{current_time} {func.__name__} run
    ')
                res = func(*args, **kwargs)
                return res
            return wrapper
        return outter
    
    
    @tail_log(path='access.log')
    def f1():
        print('f1正在执行...')
    
    f1()
    
    结果展示:
    2020-03-24 16:14:41 f1 run
    

    4、基于迭代器的方式,用while循环迭代取值字符串、列表、元组、字典、集合、文件对象

    def run(obj):
        obj_iterator = obj.__iter__()
        while True:
            try:
                print(next(obj_iterator), end=' ')
            except StopIteration:
                break
    
    
    str_obj = 'hello'
    list_obj = [1, 2, 3, 4]
    tuple_obj = (5, 6, 7, 8)
    dic_obj = {'name': 'egon', 'age': 18}
    set_obj = {10, 11, 12, 13}
    
    run(str_obj) #h e l l o
    run(list_obj) #1 2 3 4
    run(tuple_obj) #5 6 7 8
    run(dic_obj) #name age
    run(set_obj) #10 11 12 13
    
    with open('a.txt', 'r', encoding='utf-8')as f:
        run(f) 
       
    '''
    111
    222
    333
    '''
    

    5、自定义迭代器实现range功能

    def my_range(start, stop, step=2):
        while start < stop:
            yield start
            start += step
    
    g = my_range(0,5)
    print(g)
    res = next(g)
    print(res) #0
    res = next(g)
    print(res) #2
    res = next(g)
    print(res) #4
    res = next(g)
    print(res) #抛出异常
    
    
  • 相关阅读:
    BZOJ 3881: [Coci2015]Divljak
    BZOJ 2434: [Noi2011]阿狸的打字机
    BZOJ 2580: [Usaco2012 Jan]Video Game
    BZOJ 3940: [Usaco2015 Feb]Censoring
    BZOJ 3942: [Usaco2015 Feb]Censoring
    PTA L2-002 链表去重 团体程序设计天梯赛-练习集
    PTA L2-001 紧急救援-最短路(Dijkstra)多条最短路找最优解并输出路径 团体程序设计天梯赛-练习集
    PTA L1-020 帅到没朋友 团体程序设计天梯赛-练习集
    Codeforces 429 B. Working out-dp( Codeforces Round #245 (Div. 1))
    HDU 6467.简单数学题-数学题 (“字节跳动-文远知行杯”广东工业大学第十四届程序设计竞赛)
  • 原文地址:https://www.cnblogs.com/xy-han/p/12560638.html
Copyright © 2020-2023  润新知