---
title: "给函数添加装饰方法（一个二逼大学同学的故事）"
author: "郭广川"
date: "2013-12-31T15:18:15Z"
tags: []
categories: ["编程语言"]
slug: "untitled"
draft: false
lastmod: "2013-12-31T15:28:37Z"
id: 1997754
url: "https://mzhx-com.iteye.com/blog/1997754"
---

给大家讲一个我的一个二逼大学同学的故事：

 

有一个函数func\_a（arg），他有这么一种需求，想在该函数执行前和执行后加入处理逻辑，按照平常的思路他是这么进行设计的：

def func\_a(arg):

    ……

def func\_b(arg):

    …… # do something before

    func\_a(arg)

    …… # do something after 

然后他在他的程序中需要用到func\_b(arg)的地方都写上该函数的调用，并且他调用的地方很多，而有一天他的老板对他说：你的函数处理之前和处理之后的逻辑需要变更，为了应对新需求，他如此做：定义一个新的函数

def func\_c(arg):

    …… # do something before

    func\_a(arg)

    …… # do something after 

之所以他没有直接在func\_b上修改而是新建了一个func\_c是因为func\_b中的do something对他来说比较重要，他担心他老板明天让他把逻辑又还原回func\_b，所以聪明的他对func\_b进行了备份不更改，而是新建了func\_c，可是问题来了，他不得不ctrl+f查找所有文件中的func\_b，然后替换成func\_c，可怜的是，调用func\_b的地方很多，他自觉蛋疼无比，不得不带着烦躁的心一个接一个的替换，下班前他终于修改好了，信心满满的提交修改后的代码，可是第二天，fuck，他发现程序运行出错，原因是有个func\_b忘了替换

，于是老板把他叫到办公室。。。

知道他的遭遇，我表示万分同情，于是我告诉他：你可以这么做，我给了他一个小示例：

```
def func_decorate1(func):
    def check(arg):
        print 'Before the function execution, you can do thing here(func_decorate1)'
        func(arg)    
        print 'After the function execution, you can do thing here(func_decorate1)'
    return check

def func_decorate2(func):
    def check(arg):
        print 'Before the function execution, you can do thing here(func_decorate2)'
        func(arg)    
        print 'After the function execution, you can do thing here(func_decorate2)'
    return check

@func_decorate1 # here!!!!!!!
def my_func(arg):
    print arg

my_func('My function is being executed')
```

 运行结果是：

Before the function execution, you can do thing here(func\_decorate1)  
My function is being executed  
After the function execution, you can do thing here(func\_decorate1)

 

```
def func_decorate1(func):   
    def check(arg):   
        print 'Before the function execution, you can do thing here(func_decorate1)'  
        func(arg)       
        print 'After the function execution, you can do thing here(func_decorate1)'  
    return check   
  
def func_decorate2(func):   
    def check(arg):   
        print 'Before the function execution, you can do thing here(func_decorate2)'  
        func(arg)       
        print 'After the function execution, you can do thing here(func_decorate2)'  
    return check   
  
@func_decorate2 # here!!!!!!!   
def my_func(arg):   
    print arg   
  
my_func('My function is being executed')  
```

  

运行结果是：

Before the function execution, you can do thing here(func\_decorate2)  
My function is being executed  
After the function execution, you can do thing here(func\_decorate2)

 

他看了看，笑了笑，默默的回到了他的工位上，敲！代！码！！！！

 

如果看客们没懂，就看看我的这个二逼大学同学的一篇垃圾博客吧，或许会对你有些帮助，反正他的博客我已经无法直视了，欢迎吐槽

 [http://blog.csdn.net/u011252084/article/details/14448179](http://blog.csdn.net/u011252084/article/details/14448179)