Discuss / Python / 博主好牛逼,以后多来学习

博主好牛逼,以后多来学习

Topic source

_ForrestGump

#1 Created at ... [Delete] [Delete and Lock User]
def log(arg):
    text = '' if hasattr(arg, '__call__') else arg    
    def decorator(func):
        @functools.wraps(func)
        def wrapper(*args, **kw):
            print('begin %s %s:' % (text, func.__name__))
            func(*args, **kw)
            print('end %s %s:' % (text, func.__name__))
        return wrapper
    return decorator(arg) if hasattr(arg, '__call__') else decorator

uvscjh

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

膜拜

scut罗文兴

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

hasattr可以用callable代替

x1ang_li

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

赞!这是正解。

话说python的装饰器的确在设计上让人匪夷所思,对于一个通过 @foo(bar) func(...) 的,和一个 @foo func(...) 方式的,所调用的装饰器的方式是完全不用的!话说python规范为什么不改改装饰器的设计,统一用两层嵌套,让使用者和自己都更舒服一些呢……

紫系流月

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

666

Dreamgoes

#6 Created at ... [Delete] [Delete and Lock User]
text = '' if hasattr(arg, '__call__') else arg    
    ...
    return decorator(arg) if hasattr(arg, '__call__') else decorator

请问这两句是什么意思呢?没有没有参数,为何会被判为带有call属性 返回的时候还要给装饰器decorator带arg参数,装饰器的参数不是func吗 请各路大神指导下小弟,非常感谢!!!

Dreamgoes

#7 Created at ... [Delete] [Delete and Lock User]
text = '' if hasattr(arg, '__call__') else arg    
    ...
    return decorator(arg) if hasattr(arg, '__call__') else decorator

明白了,@log 不带参数,会传入需要被需要修饰的函数,所以会带call属性,再返回的时候需要继续将需要被修饰的函数作为参数继续传递到下一层。


  • 1

Reply