`
郭广川
  • 浏览: 67152 次
  • 性别: Icon_minigender_1
  • 来自: 河北
社区版块
存档分类
最新评论

给函数添加装饰方法(一个二逼大学同学的故事)

阅读更多

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

 

有一个函数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

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics