Discuss / Python / 装饰器,作业 marvin

装饰器,作业 marvin

Topic source
import functools
import time

def log2(text=None):
    def decorator(func):
        @functools.wraps(func)
        def wrapper(*args,**kw):
            if isinstance(text,(int,str)):
                print('%s begin call %s():' %(text,func.__name__))
                func(*args,**kw)
                print('%s end call %s():' %(text,func.__name__))
            else:
                print('begin call %s():' % func.__name__)
                func(*args,**kw)
                print('end call %s():' % func.__name__)
            return
        return wrapper
    return decorator if isinstance(text,(int,str)) else decorator(text) 

@log2
def now2():
    print('now is:'+time.asctime())

now2()

@log2('timeshow')
def now3():
    print('now is:'+'2017-07-10')

now3()

最后的if语句其实我是参考其他人的,但是我突然觉得很不理解, 为什么if有参数的时候是 return decorator, 而else(无参数)的时候是 return decorator(text)

谁能给解释一下。。我怎么总觉得写反了呢?不过从结果来看是对的~

小肠杆菌

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

在调试里面跑了一下,不写参数的时候,text拿到的实际是函数对象,就是本来func应该拿到的那个,结果让text提前吃掉了,截胡了你程序里的now。

这里不写字符串的话,text不会拿到None,而是直接被赋值成函数。调试里面跑到这一步,text的属性是指向一个function。

如果把return里面那个decorator(text) 直接改成decorator,执行会提示缺参数。因为内层的func这个量已经没参数可接了。

decorator(text) 的意思就是,如果发现text不是str类型,那么就是本该传给内层func的函数让外层提前拿走了,并且放在了text里面。这时应该手动把text传给里面那层,于是就return了 decorator(text)


  • 1

Reply