zoukankan      html  css  js  c++  java
  • python3练习-装饰器

      在廖雪峰的官方网站学习装饰器章节时,初步理解类似与面向切面编程。记录一下自己的课后习题解法。

    问题:
    请编写一个decorator,能在函数调用的前后打印出'begin call''end call'的日志。
    写出一个@log的decorator,使它既支持:
    @log
    def f():
        pass

    又支持:
    @log('execute')
    def f():
        pass
    示例代码(个人练习,如有问题欢迎斧正):
    # ! usr/bin/env python3
    # -*- coding:utf-8 -*-
    
    
    import functools
    
    def log(*text):
        def decorator(func):
            @functools.wraps(func)
            def warpper(*args,**kw):
                if(isinstance(text,(list,tuple))):
                    print('Info:' , text)
                    print('begin call %s():' % func.__name__)
                else:
                    print('begin call %s():' % func.__name__)
                func(*args,**kw)
                print('-------','end call %s():' % func.__name__,'--------------')
            return warpper
        return decorator
    
    @log(['execute','beginOtherInfo'])
    def now():
        print('test function')
    
    @log()
    def now2():
        print('test function2')
    now() now2()
  • 相关阅读:
    100-days: twelve
    100-days: eleven
    100-days: ten
    [PKUWC 2018]随机算法
    [CTSC 2018]假面
    APIO 2018 游记
    CTSC 2018 游记
    [CQOI 2018]解锁屏幕
    [CQOI 2018]九连环
    [CQOI 2018]破解D-H协议
  • 原文地址:https://www.cnblogs.com/GYoungBean/p/6268662.html
Copyright © 2011-2022 走看看