在python装饰器中自我

CGG*_*GJE 4 python decorator self

我想要一个装饰器,将装饰的函数添加到列表中,如下所示:

class My_Class(object):

    def __init__(self):
        self.list=[]

    @decorator
    def my_function(self)
       print 'Hi'
Run Code Online (Sandbox Code Playgroud)

我希望将my_function添加到self.list,但我不能写这个装饰器.如果我尝试在My_Class中编写它,那么我将不得不使用@ self.decorator,并且self不存在,因为我们在任何函数之外.如果我尝试用My_Class写出它,那么我就无法从my_function中检索self.

我知道存在相似的问题,但它们过于复杂,我只是在学习python和装饰器.

int*_*jay 5

您无法self从装饰器访问,因为装饰器在定义函数时运行,并且此时还没有实例My_Class.

最好将函数列表作为类属性而不是实例属性.然后,您可以将此列表作为参数传递给装饰器:

def addToList(funcList):
    '''Decorator that adds the function to a given list'''
    def actual_decorator(f):
         funcList.append(f)
         return f
    return actual_decorator

class MyClass(object):
    funcList = []

    @addToList(funcList)
    def some_function(self, name):
        print 'Hello,', name
Run Code Online (Sandbox Code Playgroud)

现在您可以访问MyClass.funcList以获取已修饰函数的列表.