Python 将类变量传递给decorator
我有一节这样的课Python 将类变量传递给decorator,python,decorator,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 Fa
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\u secondary\u id
功能中,我在orig\u data
中深度复制了我的当前\u数据
,执行一些操作,如果操作中途失败,我会将orig\u数据
复制到当前\u数据
。我必须在其他函数中执行类似的操作,比如处理其他属性等等
因此,我们的想法是对self.current_data
执行一系列操作,并保存中间结果,以防任何一个操作失败,将先前保存的状态复制到current_data
并继续。但是我想避免编写try:except:block
。我想通过将businesslogic
对象传递给decorator来为它编写一个decorator,但我不确定如何做到这一点self
只是发送给该方法的一个参数。您可以在decorator包装函数中捕获它,如下所示:
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
你试过什么吗?你到底在哪里被卡住了?