Discuss / Python / 交作业!!

交作业!!

Topic source

纯新手!!头大了好几个小时才找到失败的原因 没有TEXT的情况下,return decorator要把函数当参数传入才行 还是懵懂

#-*- coding:utf-8 -*-

import functools

def log(arg):
    switch = 1 if callable(arg) else 0         #传入的是函数开关就为1,方便后面判断
    def decorator(func):
        @functools.wraps(func)
        def wrapper(*args,**kw):
            print('='*30)                       #强迫症的分隔线 没用
            output = '@log%s(%s)' % ('' if switch else '(\'%s\')' % arg,func.__name__)                                              #先格式化要输出的LOG字符串
            print('Begin call: %s' % output)
            end = 'End call: %s' % output
            return (func(*args,**kw),print(end))     #END好像也不是一定要最后输出吧
                                                     #强迫症伤不起
        return wrapper
    return decorator(arg) if switch else decorator    #这步卡了老子好几个小时
                                                      #关键还没整太明白。。

@log('Hello')
def myfunc1():
    print('myfunc1')
    pass

@log
def myfunc2():
    print('myfunc2')
    pass

myfunc1()
myfunc2()

运行结果:

==============================
Begin call: @log('Hello')(myfunc1)
myfunc1
End call: @log('Hello')(myfunc1)
==============================
Begin call: @log(myfunc2)
myfunc2
End call: @log(myfunc2)

膜拜各位的智商,我废了,就这基础教程都玩不转!


  • 1

Reply