How to pass a class variable to a decorator inside class definition?

只愿长相守 提交于 2019-12-05 06:03:18

This is a little tricky, because you want to do several things, each of them a little finicky: (1) you want to pass an argument to a decorator and (2) you want that argument to refer to the instance, but the instance doesn't exist at the time of decoration, so we'll have to defer it somehow. You could use a function, or an itemgetter, but here I'll use a string, and I won't use functools.wraps like I should 'cause I'm lazy.

Something like:

# 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

should work:

>>> a = my_class()
>>> print a.var
None
>>> a.printout()
>>> a.var = 'apple'
>>> a.printout()
apple
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!