将类变量传递给装饰器

时间:2016-02-16 12:00:11

标签: python decorator

我有一个这样的课程

class BusinessLogic(object):
def __init__(self):
    self.url_context = None
    self.attribute_info = None
    self.current_data = None

def __nonzero__(self):
    if self.url_context and self.current_data:
        return True
    return False

def clean_up(self):
    self.url_context = None
    self.current_data = None

def set_current_info(self, url_context, data):
    self.url_context = url_context
    self.current_data = sku_data

def handle_secondary_id(self):
    try:
        orig_data = copy.deep_copy(self.current_data)
        keep_secondary_id = self.url_context.layout.get('Secondary_Id', False)
        if not keep_secondary_id and ATTRIBUTE_SECONDARY_ID in self.current_data.attributes:
            del self.current_data.attributes[ATTRIBUTE_SECONDARY_ID]
    except Exception, e:
        print "Error!!!"
        self.current_data = orig_data

def process_sku(self):
    if self:
        self.handle_secondary_id()
        # Can have multiple functions below
        #self.handle_other_attributes()
    return self.current_sku_data

基本上在我的handle_secondary_id函数中,我在current_data中制作了orig_data的深层副本,执行了一些操作,如果操作失败,则复制orig_datacurrent_data。我必须在handle_other_attributes之类的其他函数中执行类似的操作,依此类推。

因此,我们的想法是在self.current_data上执行一系列操作并保存中间结果,以防任何一个操作失败时将先前保存的状态复制到current_data并继续。但我想避免写try: except: block。我想通过将BussinessLogic对象传递给装饰器来为它编写装饰器,但我不知道该怎么做

1 个答案:

答案 0 :(得分:2)

self只是发送给方法的参数。您可以在装饰器包装函数中捕获它,如下所示:

def MyDecorator(f):
    def wrapper(*args):
        print args[0].x
        return f(*args)
    return wrapper

class C(object):
    def __init__(self):
        self.x = 1
    @MyDecorator
    def do(self):
        print 'do'

c = C()
c.do()

产量

1
do