裝飾器之前要先說說函數名()和函數名的區別
def test():
print(2)
return 2
test()是返回函數值,所以是可以賦值給變量的。比如a=test()。
test是調用函數,在scrapy里有很多的callback=self.parse
,就是調用具體函數。
裝飾器是由里外兩層函數,一般里面的函數是主函數,比如網頁里各個網頁,外層函數是里層函數執行前后要執行的函數,比如看網頁之前要看你登陸沒有這種。
通用格式是:
def outer_func(func):
def inner_func(*args, **kwargs):
#dosomething before the actual func
result = actual_func(*args, **kwargs)
#dosomething with resule before the actual func
return result
return inner_fun
調用是這樣的
@outer_func
def actual_func(*args, **kwargs):
#blalala...
actual_func()
如果要傳參給外層函數則是這樣的:
def outer_func(decorator_args):
def args_func(func):
def inner_func(*args, **kwargs):
#dosomething before the actual func
result = actual_func(*args, **kwargs)
#dosomething with resule before the actual func
return result
return inner_func
return args_func
@outer_func(decorator_args)
def actual_func(*args, **kwargs):
#blalala...