Discuss / Python / 参照评论答案做了下,依旧有点懵。

参照评论答案做了下,依旧有点懵。

Topic source

Eliefly

#1 Created at ... [Delete] [Delete and Lock User]
# callable(object)
# 中文说明:检查对象object是否可调用。如果返回True,object仍然可能调用失败;
# 但如果返回False,调用对象ojbect绝对不会成功。

import functools
def log(msg):
    if callable(msg):    #判断log的参数是否可以调用
        func=msg    #相当于执行了语句 f = log(f),f是可调用的。
        def wrapper(*args,**kw):
            print('begin call %s():' % func.__name__)
            func(*args,**kw)
            print('end call')            
        return wrapper    
    else:
        text=msg    #相当于执行了语句 f = log('execute')(f),'execute'是不可调用的。
        def decorator(func):
            def wrapper(*args,**kw):
                print('begin call')
                print('%s %s():' % (text,func.__name__))
                func(*args,**kw)
                print('end call')            
            return wrapper
        return decorator

@log    #把@log放到f()函数的定义处,相当于执行了语句 f = log(f)
def f():
    print('2015-12-29')    

# >>> f()
# begin call f():
# 2015-12-29
# end call    

@log('execute')        #相当于执行了语句 f = log('execute')(f)
def f():
    print('2015-12-29')    

# >>> f()
# begin call
# execute f():
# 2015-12-29
# end call

  • 1

Reply