zoukankan      html  css  js  c++  java
  • 当日作业 3/24

    作业错误:装饰器里竟然不调用函数?要装饰器干啥的?不就是为了扩展函数的功能???

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

    def auth(style):
        def deco(func):
            def wrapper(*args,**kwargs):
                user = input('name:').strip()
                pwd = input('password:').strip()
                if style == 'file':
                    print('基于文件校验')
                elif style == 'msql':
                    print('基于数据库校验')
                elif style == 'ldap':
                    print('基于ldap校验')
                else:
                    print('no')
                res = func()
                return res
            return wrapper
        return deco
    
    @auth('ldap')
    def func():
        print('good')
    
    func()
    

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

    dic = {}
    x = 0
    def auth(d):
        def outter(func):
            def wrapper(*args,**kwargs):
                global x
                print(x)
                d[str(x)] = func
                x += 1
            return wrapper
        return outter
    
    @auth(dic)
    def func1():
        pass
    @auth(dic)
    def func2():
        pass
    @auth(dic)
    def func3():
        pass
    
    func1()
    func2()
    func3()
    print(dic)
    

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

    def auth(path):
        def outter(func):
            def wrapper(*args, **kwargs):
                import time
                time1 = time.strftime('%Y-%m-%d %X')
                with open(r'{}'.format(path), 'a', encoding='utf-8') as f:
                    f.write('{} {} run
    '.format(time1, func.__name__))
    
            return wrapper
    
        return outter
    
    
    @auth('tank.txt')
    def func1():
        pass
    
    
    func1()
    

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

    def for1(l):
        l = l.__iter__()
        while True:
            try:
                print(l.__next__())
            except:
                break
    l = 'abcde'
    for1(l)
    

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

    def range_my(start,end,step = 1):
        while True:
            if step > 0:
                if start < end:
                    yield start
                    start += step
                else:
                    break
            else:
                if start > end:
                    yield start
                    start += step
                else:
                    break
    
    g = range_my(0,5,2)
    
    for i in g:
        print(i)
    
  • 相关阅读:
    vue 同页面不同参数
    vue的data用到this问题
    vue轮播,不是只有左右切换的,还有只切换src的
    vue页面高度填充,不出现滚动条
    WdatePicker做出onchange效果
    总结最近移动端遇到的坑(auto-size + zepto)
    react
    ES6-set && 数组剔重
    [置顶] Jquery easyui+Jsonp+asp.net+翻页 事件版
    扩展Jquery easyui的validator插件
  • 原文地址:https://www.cnblogs.com/pythonwl/p/12560295.html
Copyright © 2011-2022 走看看