---
title: "Python decorator"
author: "hfeeqi"
date: "2007-04-08T12:47:34Z"
tags: []
slug: "python-decorator"
draft: false
lastmod: "2007-04-08T12:47:34Z"
id: 68993
url: "https://hfeeqi.iteye.com/blog/68993"
---

function decorator:  
**语法:**  
@decoratorname  
def decoratoredfunction

例如:

python 代码

 

1. class C:
2. @classmethod
3. def meth(cls):
4. ...

上面的 @classmethod 等于 meth=classmethod(meth)

decorator 能够用于为函数(普通函数或类的成员函数)添加功能, 不能够用来为类动态添加方法.  
decorator 把被修饰的函数作为参数, 其返回值通常是一个函数或者类

技术上讲, 任何只带一个参数能够被调用的对象都可以被当作decorator使用, 但是这个定义过于宽泛而无用, 所以可以把decorator分为以下两类:

- signature-preserving decorator: 例如, 一个输入为一个函数输出与该函数的输出一致的可调用对象
- signature-changing decorator: 例如, 内部类 staticmethod 和 classmethod 就属于这种类型, 因为它们会把被修饰的函数作为输入, 返回一个描述对象, 这个对象不是函数, 不可调用

**Decorator的用法**:

- **@catch\_on((exception list), functor)**

其定义如下:

python 代码

 

01. from types import *
02. def catch\_on(excepts, act):
03. def call(proc, \*args, \*\*kw):
04. try:
05. return proc(\*args, \*\*kw)
06. except excepts, e:
07. if not act and type(act) is types.FunctionType:
08. act(e)
09. pass
10. except Exception, e:
11. if not isinstance(e, excepts):
12. raise
13. return decorator(call)
14. def x():
15. raise NameError, "NameError"
16. def boo():
17. raise KeyError, "KeyError"
18. def bar():
19. raise ValueError, "ValueError"
20. @catch\_on((KeyError, ValueError), lambda e: None)
21. def koo():
22. x()
23. boo()
24. bar()
25. @catch\_on((KeyError, ValueError), lambda e: None)
26. def goo():
27. boo()
28. bar()
29. x()
30. koo()
31. goo()

<!--THE END-->

- 代码块