Discuss / Python / decorator

decorator

Topic source

YOUTH

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

def metric(fn):

    @functools.wraps(fn)

    def wrapper(*args,**kw):

        t1= time.time()

        fc = fn(*args,**kw) # 执行函数

        t2 = time.time()

         print('%s executed in %s ms' % (fn.__name__, t2-t1))

        return fc # 返回值

    return wrapper

YOUTH

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

学习了评论区,自己理解的还是不到位

def log(text):    @functools.wraps(text)    def decorator(func):        @functools.wraps(func)        def wrapper(*args, **kw):            if type(text) != str:                print('%s is called'% func.__name__)                print('None Text')            else:                print('%s is called'% func.__name__)                print('Text is : execute')            return func(*args, **kw)        return wrapper        #要分别处理    if isinstance(text,str):        return decorator    else:        return decorator(text)

这两个判断不是很理解,为什么要这样写?

ゆうき

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

同问,为什么当不传入参数的时候最后返回的反而是是decorator(text),这时候text 不是等于空吗?


  • 1

Reply