我想要一个装饰器,它可以将装饰函数添加到列表中,如下所示:
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/