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()
原文地址:https://www.cnblogs.com/GYoungBean/p/6268662.html