Discuss / Python / 教程里没有说清楚装饰器的赋值机制

教程里没有说清楚装饰器的赋值机制

Topic source

UTOO_NAIVE

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

我猜是如果log()没有参数,就会直接把函数当成第一个参数赋值给log()里的text。python的闭包好难看懂啊,人生苦短,我用java。

# -*- coding: utf-8 -*-
import functools
from inspect import isfunction
def log(text=''):
    def outFun(fn):
        @functools.wraps(fn)
        def inFun(*args, **km):
            message = text if type(text) is str else ''
            print('print :%s %s' % (message, fn.__name__))
            return fn(*args, **km)

        return inFun

    if type(text) is str:
        return outFun
    elif isfunction(text):
        return outFun(text)

@log
def f1():
    print('这里call f1()')

@log('execute')
def f2():
    print('这里call f2()')

f1()
f2()

  • 1

Reply