Python@TW: 會眾| IRC| Planet| 郵件列表| 聯絡我們
修訂版 2 和 6 的差異如下: (間隔 4 版)
2007-02-23 00:11:46 修訂第 2 版
大小: 1115
編輯者: Thinker
說明:
2007-05-02 14:55:18 修訂第 6 版
大小: 1201
編輯者: yungyuc
說明: restructure
這個顏色代表刪除的 這個顏色代表增加的
行號 1: 行號 1:
## page was renamed from decorator
行號 3: 行號 4:
{{{ {{{#!python
行號 9: 行號 10:
{{{ {{{#!python
行號 15: 行號 16:
check_div_zero 是一個 function 或者任何 callable,接受另一個 callable 為參數,並傳回另一個 callable。這樣做的目的,是為了提供一些包裝的功能,將一些功能加到原本的 callable 上面。例如上例,就可以除零的檢查加上去。 check_div_zero 是一個 function 或者任何 callable,接受另一個 callable 為參數,並傳回另一個 callable。這樣做的目的,是為了提供一些包裝的功能,將一些功能加到原本的 callable 上面。例如上例,就可以除零的檢查加上去。
行號 17: 行號 18:
{{{ {{{#!python
行號 28: 行號 29:

----
CategoryCookbook

decorator

Python 能以 decorator 包裝其它的 function 、method 、或 lambda 等,任何 callable object 。嚴格來說, decorator 並不是什麼偉大的發明,它只是讓我們少打幾個字來完成特定的工作。例如:

   1 @check_div_zero
   2 def div(a, b):
   3     return a / b

這段 code ,其實等於

   1 def div(a, b):
   2     return a / b
   3 div = check_div_zero(div)

check_div_zero 是一個 function 或者任何 callable,接受另一個 callable 為參數,並傳回另一個 callable。這樣做的目的,是為了提供一些包裝的功能,將一些功能加到原本的 callable 上面。例如上例,就可以將除零的檢查加上去。

   1 def check_div_zero(func):
   2     def deco(a, b):
   3         if a * b == 0:
   4             alert(".....")
   5             return
   6         func(a, b)
   7     return deco

這就是一個簡單的 decorator。 Programmer 可以將一些大量使用到的檢查;例如:權限檢查,寫成 decorator 並 wrap 在需要的 method 或 function 上。如此能大量的減少 code 的重複,也更簡單易懂。


CategoryCookbook

Python/Cookbook/Decorator (上次是 localhost 在 2009-04-01 04:14:21 編輯的)