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

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

 

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值