Discuss / Python / 同时实现@log跟@log(‘xx’)不过在判断isinstance(txt,function)会出现未定义错误,不知道为什么,只能改用 isinstance(txt,(str,int))判断了

同时实现@log跟@log(‘xx’)不过在判断isinstance(txt,function)会出现未定义错误,不知道为什么,只能改用 isinstance(txt,(str,int))判断了

Topic source
import functools
def log(txt):
    if isinstance(txt,(str,int)):
        def decorator(func):
            @ functools.wraps(func)
            def wrapper(*args,**kw):
                print('%s begin call %s' %(txt,func.__name__))
                we= func(*args,**kw)
                print(we)
                print('%s end call %s' %(txt,func.__name__))
            return wrapper
        return decorator
    else:
        @ functools.wraps(txt)
        def wrapper(*args,**kw):
            print('begin call %s' % txt.__name__)
            we= txt(*args,**kw)
            print(we)
            print('end call %s' % txt.__name__)
        return wrapper

确定变量是否函数:

方法1:(这个貌似最好用) callable(fn) //返回True或False

方法2: hasattr(fn, '__call__') //返回True或False

方法3:需要引入types模块 import types isinstance(f, types.FunctionType)


  • 1

Reply