為什么在Python代碼中裝飾器很重要
01什么是裝飾器?
要理解什么是裝飾器,您首先需要熟悉Python處理函數(shù)的方式。從它的觀點(diǎn)來(lái)看,函數(shù)和對(duì)象沒有什么不同。它們有屬性,可以重新分配:
- def func():
- print('hello from func')
- func()
- > hello from func
- new_func = func
- new_func()
- > hello from func
- print(new_func.__name__)
- > func
此外,你還可以將它們作為參數(shù)傳遞給其他函數(shù):
- def func():
- print('hello from func')
- def call_func_twice(callback):
- callback()
- callback()
- call_func_twice(func)
- > hello from func
- > hello from func
現(xiàn)在,我們介紹裝飾器。裝飾器(decorator)用于修改函數(shù)或類的行為。實(shí)現(xiàn)這一點(diǎn)的方法是定義一個(gè)返回另一個(gè)函數(shù)的函數(shù)(裝飾器)。這聽起來(lái)很復(fù)雜,但是通過(guò)這個(gè)例子你會(huì)理解所有的東西:
- def logging_decorator(func):
- def logging_wrapper(*args, **kwargs):
- print(f'Before {func.__name__}')
- func(*args, **kwargs)
- print(f'After {func.__name__}')
- return logging_wrapper
- @logging_decorator
- def sum(x, y):
- print(x + y)
- sum(2, 5)
- > Before sum
- > 7
- > After sum
讓我們一步一步來(lái):
- 首先,我們?cè)诘?行定義logging_decorator函數(shù)。它只接受一個(gè)參數(shù),也就是我們要修飾的函數(shù)。
- 在內(nèi)部,我們定義了另一個(gè)函數(shù):logging_wrapper。然后返回logging_wrapper,并使用它來(lái)代替原來(lái)的修飾函數(shù)。
- 在第7行,您可以看到如何將裝飾器應(yīng)用到sum函數(shù)。
- 在第11行,當(dāng)我們調(diào)用sum時(shí),它不僅僅調(diào)用sum。它將調(diào)用logging_wrapper,它將在調(diào)用sum之前和之后記錄日志。
02為什么需要裝飾器
這很簡(jiǎn)單:可讀性。Python因其清晰簡(jiǎn)潔的語(yǔ)法而備受贊譽(yù),裝飾器也不例外。如果有任何行為是多個(gè)函數(shù)共有的,那么您可能需要制作一個(gè)裝飾器。下面是一些可能會(huì)派上用場(chǎng)的例子:
- 在運(yùn)行時(shí)檢查實(shí)參類型
- 基準(zhǔn)函數(shù)調(diào)用
- 緩存功能的結(jié)果
- 計(jì)數(shù)函數(shù)調(diào)用
- 檢查元數(shù)據(jù)(權(quán)限、角色等)
- 元編程
和更多…
現(xiàn)在我們將列出一些代碼示例。
03例子
帶有返回值的裝飾器
假設(shè)我們想知道每個(gè)函數(shù)調(diào)用需要多長(zhǎng)時(shí)間。而且,函數(shù)大多數(shù)時(shí)候都會(huì)返回一些東西,所以裝飾器也必須處理它:
- def timer_decorator(func):
- def timer_wrapper(*args, **kwargs):
- import datetime
- before = datetime.datetime.now()
- result = func(*args,**kwargs)
- after = datetime.datetime.now()
- print "Elapsed Time = {0}".format(after-before)
- return result
- @timer_decorator
- def sum(x, y):
- print(x + y)
- return x + y
- sum(2, 5)
- > 7
- > Elapsed Time = some time
可以看到,我們將返回值存儲(chǔ)在第5行的result中。但在返回之前,我們必須完成對(duì)函數(shù)的計(jì)時(shí)。這是一個(gè)沒有裝飾者就不可能實(shí)現(xiàn)的行為例子。
帶有參數(shù)的裝飾器
有時(shí)候,我們想要一個(gè)接受值的裝飾器(比如Flask中的@app.route('/login'):
- def permission_decorator(permission):
- def _permission_decorator(func):
- def permission_wrapper(*args, **kwargs):
- if someUserApi.hasPermission(permission):
- result = func(*args, **kwargs)
- return result
- return None
- return permission wrapper
- return _permission_decorator
- @permission_decorator('admin')
- def delete_user(user):
- someUserApi.deleteUser(user)
為了實(shí)現(xiàn)這一點(diǎn),我們定義了一個(gè)額外的函數(shù),它接受一個(gè)參數(shù)并返回一個(gè)裝飾器。
帶有類的裝飾器
使用類代替函數(shù)來(lái)修飾是可能的。唯一的區(qū)別是語(yǔ)法,所以請(qǐng)使用您更熟悉的語(yǔ)法。下面是使用類重寫的日志裝飾器:
- class Logging:
- def __init__(self, function):
- self.function = function
- def __call__(self, *args, **kwargs):
- print(f'Before {self.function.__name__}')
- self.function(*args, **kwargs)
- print(f'After {self.function.__name__}')
- @Logging
- def sum(x, y):
- print(x + y)
- sum(5, 2)
- > Before sum
- > 7
- > After sum
這樣做的好處是,您不必處理嵌套函數(shù)。你所需要做的就是定義一個(gè)類并覆蓋__call__方法。
裝飾類
有時(shí),您可能想要修飾類中的每個(gè)方法。你可以這樣寫
- class MyClass:
- @decorator
- def func1(self):
- pass
- @decorator
- def func2(self):
- pass
但如果你有很多方法,這可能會(huì)失控。值得慶幸的是,有一種方法可以一次性裝飾整個(gè)班級(jí):
- def logging_decorator(func):
- def logging_wrapper(*args, **kwargs):
- print(f'Before {func.__name__}')
- result = func(*args, **kwargs)
- print(f'After {func.__name__}')
- return result
- return logging_wrapper
- def log_all_class_methods(cls):
- class NewCls(object):
- def __init__(self, *args, **kwargs):
- self.original = cls(*args, **kwargs)
- def __getattribute__(self, s):
- try:
- x = super(NewCls,self).__getattribute__(s)
- except AttributeError:
- pass
- else:
- return x
- x = self.original.__getattribute__(s)
- if type(x) == type(self.__init__):
- return logging_decorator(x)
- else:
- return x
- return NewCls
- @log_all_class_methods
- class SomeMethods:
- def func1(self):
- print('func1')
- def func2(self):
- print('func2')
- methods = SomeMethods()
- methods.func1()
- > Before func1
- > func1
- > After func1
現(xiàn)在,不要驚慌。這看起來(lái)很復(fù)雜,但邏輯是一樣的:
- 首先,我們讓logging_decorator保持原樣。它將應(yīng)用于類的所有方法。
- 然后我們定義一個(gè)新的裝飾器:log_all_class_methods。它類似于普通的裝飾器,但卻返回一個(gè)類。
- NewCls有一個(gè)自定義的__getattribute__。對(duì)于對(duì)原始類的所有調(diào)用,它將使用logging_decorator裝飾函數(shù)。
內(nèi)置的修飾符
您不僅可以定義自己的decorator,而且在標(biāo)準(zhǔn)庫(kù)中也提供了一些decorator。我將列出與我一起工作最多的三個(gè)人:
@property -一個(gè)內(nèi)置插件的裝飾器,它允許你為類屬性定義getter和setter。
@lru_cache - functools模塊的裝飾器。它記憶函數(shù)參數(shù)和返回值,這對(duì)于純函數(shù)(如階乘)很方便。
@abstractmethod——abc模塊的裝飾器。指示該方法是抽象的,且缺少實(shí)現(xiàn)細(xì)節(jié)。