# 你的第一個裝飾器
# 你的第一個裝飾器
在上一個例子里,其實我們已經創建了一個裝飾器!現在我們修改下上一個裝飾器,并編寫一個稍微更有用點的程序:
~~~
def a_new_decorator(a_func):
def wrapTheFunction():
print("I am doing some boring work before executing a_func()")
a_func()
print("I am doing some boring work after executing a_func()")
return wrapTheFunction
def a_function_requiring_decoration():
print("I am the function which needs some decoration to remove my foul smell")
a_function_requiring_decoration()
#outputs: "I am the function which needs some decoration to remove my foul smell"
a_function_requiring_decoration = a_new_decorator(a_function_requiring_decoration)
#now a_function_requiring_decoration is wrapped by wrapTheFunction()
a_function_requiring_decoration()
#outputs:I am doing some boring work before executing a_func()
# I am the function which needs some decoration to remove my foul smell
# I am doing some boring work after executing a_func()
~~~
你看明白了嗎?我們剛剛應用了之前學習到的原理。這正是python中裝飾器做的事情!它們封裝一個函數,并且用這樣或者那樣的方式來修改它的行為。現在你也許疑惑,我們在代碼里并沒有使用@符號?那只是一個簡短的方式來生成一個被裝飾的函數。這里是我們如何使用@來運行之前的代碼:
~~~
@a_new_decorator
def a_function_requiring_decoration():
"""Hey you! Decorate me!"""
print("I am the function which needs some decoration to "
"remove my foul smell")
a_function_requiring_decoration()
#outputs: I am doing some boring work before executing a_func()
# I am the function which needs some decoration to remove my foul smell
# I am doing some boring work after executing a_func()
#the @a_new_decorator is just a short way of saying:
a_function_requiring_decoration = a_new_decorator(a_function_requiring_decoration)
~~~
希望你現在對Python裝飾器的工作原理有一個基本的理解。如果我們運行如下代碼會存在一個問題:
~~~
print(a_function_requiring_decoration.__name__)
# Output: wrapTheFunction
~~~
這并不是我們想要的!Ouput輸出應該是“a_function_requiring_decoration”。這里的函數被warpTheFunction替代了。它重寫了我們函數的名字和注釋文檔(docstring)。幸運的是Python提供給我們一個簡單的函數來解決這個問題,那就是functools.wraps。我們修改上一個例子來使用functools.wraps:
~~~
from functools import wraps
def a_new_decorator(a_func):
@wraps(a_func)
def wrapTheFunction():
print("I am doing some boring work before executing a_func()")
a_func()
print("I am doing some boring work after executing a_func()")
return wrapTheFunction
@a_new_decorator
def a_function_requiring_decoration():
"""Hey yo! Decorate me!"""
print("I am the function which needs some decoration to "
"remove my foul smell")
print(a_function_requiring_decoration.__name__)
# Output: a_function_requiring_decoration
~~~
現在好多了。我們接下來學習裝飾器的一些常用場景。
藍本規范:
~~~
from functools import wraps
def decorator_name(f):
@wraps(f)
def decorated(*args, **kwargs):
if not can_run:
return "Function will not run"
return f(*args, **kwargs)
return decorated
@decorator_name
def func():
return("Function is running")
can_run = True
print(func())
# Output: Function is running
can_run = False
print(func())
# Output: Function will not run
~~~
注意:@wraps接受一個函數來進行裝飾,并加入了復制函數名稱、注釋文檔、參數列表等等的功能。這可以讓我們在裝飾器里面訪問在裝飾之前的函數的屬性。
- 簡介
- 序
- 譯后感
- 原作者前言
- *args 和 **kwargs
- *args 的用法
- **kwargs 的用法
- 使用 *args 和 **kwargs 來調用函數
- 啥時候使用它們
- 調試 Debugging
- 生成器 Generators
- 可迭代對象(Iterable)
- 迭代器(Iterator)
- 迭代(Iteration)
- 生成器(Generators)
- Map和Filter
- Map
- Filter
- set 數據結構
- 三元運算符
- 裝飾器
- 一切皆對象
- 在函數中定義函數
- 從函數中返回函數
- 將函數作為參數傳給另一個函數
- 你的第一個裝飾器
- 使用場景
- 授權
- 日志
- 帶參數的裝飾器
- 在函數中嵌入裝飾器
- 裝飾器類
- Global和Return
- 多個return值
- 對象變動 Mutation
- slots魔法
- 虛擬環境
- 容器 Collections
- 枚舉 Enumerate
- 對象自省
- dir
- type和id
- inspect模塊
- 推導式 Comprehension
- 列表推導式
- 字典推導式
- 集合推導式
- 異常
- 處理多個異常
- finally從句
- try/else從句
- lambda表達式
- 一行式
- For - Else
- else語句
- open函數
- 目標Python2+3
- 協程
- 函數緩存
- Python 3.2+
- Python 2+
- 上下文管理器
- 基于類的實現
- 處理異常
- 基于生成器的實現