我想使用一个接受一个参数的装饰器,检查该参数是否为None,如果是True则让装饰函数运行。
我想在类定义中使用这个装饰器,因为我有一组类方法,它们首先检查特定的类变量是否为None。我认为如果我使用装饰器会更好看。
我想做这样的事情:
# decorator
def variable_tester(arg):
def wrap(f):
def wrapped_f(*args):
if arg is not None:
f(*args)
else:
pass
return wrapped_f
return wrap
# class definition
class my_class(object):
def __init__(self):
self.var = None
@variable_tester(self.var) # This is wrong. How to pass self.var to decorator?
def printout(self):
print self.var
def setvar(self, v):
self.var = v
# testing code
my_instance = my_class()
my_instance.printout() # It should print nothing
my_instance.setvar('foobar')
my_instance.printout() # It should print foobar
答案 0 :(得分:5)
这有点棘手,因为你想要做几件事,每件事都有点挑剔:(1)你想把一个参数传递给装饰者,(2)你想让那个参数引用实例,但是这个实例在装饰时并不存在,所以我们不得不以某种方式推迟它。你可以使用一个函数,或itemgetter
,但在这里我会使用一个字符串,我不会像我应该使用functools.wraps
那样因为我很懒。
类似的东西:
# really, it's variable-tester-factory
def variable_tester(target):
def deco(function):
def inner(self, *args, **kwargs):
if getattr(self, target) is not None:
return function(self, *args, **kwargs)
return inner
return deco
class my_class(object):
def __init__(self):
self.var = None
@variable_tester('var')
def printout(self):
print self.var
应该有效:
>>> a = my_class()
>>> print a.var
None
>>> a.printout()
>>> a.var = 'apple'
>>> a.printout()
apple