Discuss / Python / 第一个问题不要单纯执行func的过程,注意把返回值正确返回出来

第一个问题不要单纯执行func的过程,注意把返回值正确返回出来

Topic source

Hominum

#1 Created at ... [Delete] [Delete and Lock User]

请编写一个decorator,能在函数调用的前后打印出'begin call''end call'的日志。

def log(func):
    def wrapper(*args, **kw):
        print('before call %s' % func.__name__)
        return_value = func(*args, **kw)
        print('end call %s' % func.__name__)
        return return_value
    return wrapper

@log
def sum2(a, b):
    print('%d + %d' % (a, b))
    return a + b

print(sum2(1, 2))

输出:

before call sum2
1 + 2
end call sum2
3

  • 1

Reply