Discuss / Python / 虽然运行起来了,但其实不是很懂为什么‘’else:decorator(text)‘’这里decorator为什么要加参数,求解释

虽然运行起来了,但其实不是很懂为什么‘’else:decorator(text)‘’这里decorator为什么要加参数,求解释

Topic source

Pider_Joker

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

import functools

def log(text = None): def decorator(func): @functools.wraps(func) def wrapper(args,**kw): if isinstance(text,str): print('有text:%s---%s---'%(text,func.name)) else: print('无text:---%s---'%(func.name)) return func(args,**kw) return wrapper if isinstance(text,str): return decorator else: return decorator(text) '''

@log('execute') def g(): print('Hello World 哥!') g()

@log def f(): print('Hello World 姐!') f()

Pider_Joker

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

看了楼下的明白了,是@log 和@log()的指向问题

Pider_Joker

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

有输入'execute'的三层def,没输入的两层def,用if 分开,明白了啊哈哈哈哈

twiceYuan

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

刚开始也没搞明白,主要这里 text = None 比较有迷惑性,看有个命名为 text_or_func 的更好一些,因为没有显式给出字符串参数时其实是把 func 作为了参数,然后再加入判断区分处理方法和返回的函数。

另外这里的 =None 没有必要了吧?因为如上面所说,没有显式参数时其实是有个 func 作为参数的,所以默认值 None 其实并没有用到。


  • 1

Reply