Discuss / Python / 通用的装饰器

通用的装饰器

Topic source

taogebuaa

#1 Created at ... [Delete] [Delete and Lock User]
import functools
def log(text):
    if isinstance(text,str):
        def decorator(func):
            @functools.wraps(func)
            def wrapper (*args,**kw):
                print('%s %s():' % (text,func.__name__))
                return func(*args,**kw)
            return wrapper
        return decorator
    else:

        @functools.wraps(text)
        def wrapper(*args, **kw):
            print('call %s():' % text.__name__)
            return text(*args, **kw)
        return wrapper

赞一个

这个不对吧?如果@log()的话抛出错误missing 1 required positinal argument

沙志刚

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

def log(text='Call'):

啊呜说

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

def log(text='Call'): 这样的话 判断就永远都是str了 更不对

啊呜说

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

我试了居然可以。。。。这是为什么啊,Log里的函数究竟是怎么传入。。?

余晨飞

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

def log(text=None): 这样就没问题了

请问:对于没有自身参数的装饰器,@log 和@log()有什么区别?

我注意到廖老师的教学内容里,没有参数的装饰器用的是@log,大家评论里的答案为了通用而写的装饰器,使用@log()的形式来装饰。这里头有什么坑吗?强迫症表示@log看起来舒服得多


  • 1

Reply