python装饰器带括号和不带括号的语法和用法

装饰器的写法补充:

通常装饰器的写法是@func(),而有的时候为了减少出错率,可能会写成@func,没有()括号,这时我们可以这样定义,来减少括号。下面通过两个例子还看。

一般装饰器的写法:
 1 def log(func=None):
 2     
 3     def inner(*args, **kwargs):
 4         print('do something before')
 5         res = func(*args, **kwargs)
 6         print('do something after')
 7         return rees
 8     
 9     return inner
10 
11 #使用装饰器
12 @log()
13 def my_func():
14     print('i am my_func')
15 
16 #运行这个函数
17 my_func()

运行结果:

1 do something before
2 i am my_func
3 do something after
可以不带括号的装饰器写法

需要增加判断在函数内,用于判断使用装饰器的函数是否可以调用,以达到括号的自由写法

判断的装饰器写法

 1 def log(func=None):
 2     
 3     #需要再次嵌套一层装饰器,才可以供下面运行时使用
 4     def wrapper(fun)
 5         def inner(*args, **kwargs):
 6             print('do something before')
 7             res = fun(*args, **kwargs)
 8             print('do something after')
 9             return rees
10         
11         return inner
12     
13     #判断func(参数):
14     if func is None:
15         return wrapper
16         
17     #如果func是可以调用的函数    
18     elif callable(func):
19         return wrapper(func)
20     
21 
22 #使用装饰器的时候,两种写法都可以运行
23 
24 第一种不带括号:
25 @log
26 def my_func():
27     print('i am my_func')
28 
29 第二种带括号的:
30 @log()
31 def my_func():
32     print('i am my_func')
33 
34 
35 #运行这个函数
36 my_func()

两种方式的一样,运行结果:

1 do something before
2 i am my_func
3 do something after

不带括号的理解:

 

@log =>等同于 my_func = log(my_func)

带括号的理解:

@log() =>等同于 my_func = log()(my_func)

 

结论: 内嵌之后,可以增加判断条件,增加了装饰器的灵活性。

原文地址:https://www.cnblogs.com/hua888/p/10436288.html