python装饰器使用的问题

以手指天 发布于 2012/11/01 16:01
阅读 411
收藏 0

最近要求界面能及时的更新后台逻辑的执行进度问题。目前的代码是这样的:

#coding=utf-8
'''
Created on 2012-11-1

@author: tanzhen

'''
def UpdateUI(msg, step):
    print u"内容:", msg
    print u"步骤:到第%s步了" % step
    
class Command(object):
    
    def Excute(self):
        UpdateUI("开始第一步", 1)
        self.Work1st()
        UpdateUI("开始第二步", 2)
        self.Work2nd()
        UpdateUI("开始第三步", 3)
        self.Work3rd()
    
    def Work1st(self):
        print "Work1st"
        
    def Work2nd(self):
        print "Work2nd"
        
    def Work3rd(self):
        print "Work3rd"

command = Command()
command.Excute()

这样能输出想要的结果:

内容: 开始第一步
步骤:到第1步了
Work1st
内容: 开始第二步
步骤:到第2步了
Work2nd
内容: 开始第三步
步骤:到第3步了
Work3rd

 

但是。。问题来了,在逻辑中插入刷新界面的代码感觉不爽,并且看起也麻烦,想用装饰器,但是不是很熟,写成这样:

#coding=utf-8
'''
Created on 2012-11-1

@author: tanzhen

'''
def UpdateUI(msg, step):
    def wapper(func):
        print u"内容:", msg
        func()
        print u"步骤:到第%s步了" % step
    return wapper

class Command(object):
    
    def Excute(self):
        self.Work1st()
        self.Work2nd()
        self.Work3rd()
    
    @UpdateUI("开始第一步", 1)
    def Work1st(self):
        print "Work1st"
    
    @UpdateUI("开始第二步", 2)
    def Work2nd(self):
        print "Work2nd"
    
    @UpdateUI("开始第三步", 3)
    def Work3rd(self):
        print "Work3rd"

command = Command()
command.Excute()

但是因为Workxxx函数是类函数,需要self。。所以程序会报错。。有木有高手帮小弟修改下,能达到预期的效果

加载中
0
以手指天

还是我自己来吧。这样子就OK了

#coding=utf-8
'''
Created on 2012-11-1

@author: tanzhen

'''

def UpdateUI(msg, step):
    
    def Wapper(func):

        def ChildWapper(*args, **kargs):
            print u"内容:", msg
            print u"步骤:到第%s步了" % step
            func(*args, **kargs)
            
        return ChildWapper
    return Wapper

class Command(object):
    
    def Excute(self):
        self.Work1st("Lily")
        self.Work2nd()
        self.Work3rd()
    
    @UpdateUI("开始第一步", 1)
    def Work1st(self, name):
        print "Work1st", name
    
    @UpdateUI("开始第二步", 2)
    def Work2nd(self):
        print "Work2nd"
    
    @UpdateUI("开始第三步", 3)
    def Work3rd(self):
        print "Work3rd"

command = Command()
command.Excute()

 

返回顶部
顶部