Discuss / Python / 既能@log也能@log('text')

既能@log也能@log('text')

Topic source

孝爱精进

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

import functools,time,inspect

#inspect.isfunction() 也可以判断是不是函数 def log(canshu1,*canshu2): try: if len(canshu1) != 0: if hasattr(canshu1[0],"call"): raise Exception

    if(len(canshu1) == 0 and len(canshu2) == 0):
        raise Exception

    def log2(fn):
        @functools.wraps(fn)
        def wrapper(*args, **kw):
            print("你写的有参数")
            if len(canshu1) != 0:
                print('call:%s' % fn.__name__ ,"参数是",[x for x in canshu1] )
            if len(canshu2) != 0:
                print('call:%s' % fn.__name__ ,"参数是",[(x+"=>"+y) for x,y in canshu2.items()] )
            return fn(*args, **kw)
        return wrapper
    return log2
except:
    @functools.wraps(canshu1[0])
    def wrapper(*args):
        print("你写的没有参数")
        print('call:%s' % canshu1[0].__name__)
        return canshu1[0](*args)
    return wrapper

@log def f(): print("简单调用") f()

@log(1,2,3,abc="你好",ddd="456") def f(): print("简单调用") f()

print(f.name)

孝爱精进

#2 Created at ... [Delete] [Delete and Lock User]
    1. def log(前面1个星号 canshu1,前面2个星号 canshu2): 编辑器把这个星号屏蔽了

孝爱精进

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

def log(canshu1,*canshu2):

第一句话是这个 不知道为什么发布的时候少了星号


  • 1

Reply