python - python装饰器中的 self

标签 python decorator self

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

class My_Class(object):

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

    @decorator
    def my_function(self)
       print 'Hi'

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

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

最佳答案

你不能从装饰器访问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

现在您可以访问 MyClass.funcList 以获取装饰函数列表。

关于python - python装饰器中的 self ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8375862/

相关文章:

Swift - 捕获列表 self 澄清

python - 当数据帧大小超过 100 行时,Pandas dataframe query() 会抛出错误

Python解析嵌套

python - celery 任务和自定义装饰器

ruby-on-rails - 如何从 Rails 中的 Draper 装饰器访问 session 变量?

python - 为什么在 Python 中对该项目使用装饰器时 Flask 的 url_for 会抛出错误?

objective-c - 为什么在 Objective-C 中允许 [object.delegate self]?

python - OpenCV 像人眼一样找到主观轮廓

python - 为什么这些简写不能互相使用?

python - 为什么 string.Formatter.format 没有 "self"参数?