---
title: "python小例子之8 -- decorator的使用"
author: "weistar"
date: "2014-03-19T14:40:18Z"
tags: []
categories: ["编程语言"]
slug: "python-8-decorator"
draft: true
lastmod: "2014-03-19T14:40:17Z"
id: 2032941
url: "https://weistar.iteye.com/blog/2032941"
---

文章源自：http://bluecrystal.iteye.com/blog/137462

### python小例子之8 -- decorator的使用

主题： decorator的使用

 

环境： winxp pro + sp2 + python2.5  
备注： 请注意，凡是在源代码文件中使用了中文字符，请最好保存为utf-8格式

 

              本文与另外一篇blog文章内容相关：[python中如何简单的实现decorator模式--由django admin源码所得体会](http://bluecrystal.iteye.com/blog/132934 "永久链接：python中如何简单的实现decorator模式--由django admin源码所得体会") 

 

              本文就是因[kdekid](http://kdekid.iteye.com/) 在该blog回帖后，我对python decorator的使用整理出的一点心得，在上述提及的blog中的代码亦可修改为本文所描述的方式，各位同学可自己试试 ：）

              具体的语法描述可参考： python manuals -- Language Reference -- 7.Compound statements -- 7.6 Function definitions  ![](http://bluecrystal.iteye.com/javascripts/fckeditor/editor/images/smiley/msn/lightbulb.gif)

```
    # decorator_arg.py   
      
    # 修饰函数       
    def decorator(fun):       
        def ifun(*args, **kwargs):       
            args = (i+1 for i in args)       
            return fun(*args, **kwargs)       
        return ifun       
      
    def decorator1(arg):   
        def _decorator1(fun):   
            def ifun(*args, **kwargs):   
                args = (i+arg for i in args)   
                return fun(*args, **kwargs)   
            return ifun   
        return _decorator1   
      
    # 被修饰函数1   
    @decorator   
    def fun1(x,y,z):       
        return x+y+z       
      
    arg = 2   
    # 被修饰函数2   
    @decorator1(arg)   
    def fun2(x,y,z):   
        return x+y+z   
          
    # 测试代码       
    a = 3       
    b = 4       
    c = 5   
      
    print fun1(a,b,c)   
    print fun2(a,b,c)   

```