1、装饰器带括号非括号
#不带参数的装饰器 def log4(func): @wraps(func) def inner(*args, **kwargs,): func(*args, **kwargs) return inner @log4 def test(num): print('testlog4:',num,test.__name__) test(40) #带参数的装饰器 def log5(level): def log(func): @wraps(func) def inner(*args, **kwargs,): if level == "warn": print("%s is running" % func.__name__) func(*args, **kwargs) return inner return log @log5(level="warn") def test(num): print('testlog5:', num, test.__name__) test(50)
不带参数的装饰器:带括号、不带括号的区别
#不带参数的装饰器:带括号、不带括号 from functools import wraps import time def runTime(func): @wraps(func) def inner(*args, **kwargs): s = time.time() func(*args, **kwargs) print(f'--> {func.__name__} RUN TIME: <{(time.time() - s)}> ') return inner """ @runTime 等同于 @runTime => test1 = runTime(test1) @runTime() 等同于 @inner 非装饰器 => test2 = runTime()(test2) = inner(test2) 报错 """ @runTime def test1(): pass @runTime() def test2(): pass
带参数的装饰器:带括号、不带括号的区别
#带参数的装饰器:带括号、不带括号 from functools import wraps import time def out_runTime(name='测试'): def runTime(func): @wraps(func) def inner(*args, **kwargs): s = time.time() func(*args, **kwargs) print(f'--> {func.__name__} RUN TIME: <{(time.time() - s)}> ') return inner return runTime """ @out_runTime 等同于 @out_runTime => test1 = out_runTime(test1) 报错 @out_runTime() 等同于 @runTime 返回一个装饰器 => test2 = runTime(test2) """ @out_runTime def test1(): pass @out_runTime() def test2(): pass
2、调用函数带括号非括号
""" 1、不带括号时,调用的是这个函数本身,是整个函数体,是一个函数对象 2、带括号(参数或者无参),调用的是函数的执行结果 """ def a(): return 1 print(a) print(a())