Python将self传递给装饰器

时间:2017-12-14 18:38:27

标签: python python-decorators

我正在尝试将self对象传递给我的装饰器以访问其内容但是出现以下错误:

def log_decorator():
    def log_real_decorator(f):
        @wraps(f)
        def wrapper(self,*args, **kw):      
            print "I am the decorator, I know that self is", self, "and I can do whatever I want with it!"
            print "I also got other args:", args, kw           
            f(*args, **kw)

        return wrapper        
    return log_real_decorator    

class Foo(object):
    @log_decorator

    def meth(self):
        print "I am the method, my self is", self


f = Foo()        
f.meth()

错误: -

TypeError: log_decorator() takes no arguments (1 given)

1 个答案:

答案 0 :(得分:5)

您就是这样做的:

 - Ignore this line -

只需传递def log_real_decorator(f): @wraps(f) def wrapper(self, *args, **kw): print "I am the decorator, I know that self is", self, "and I can do whatever I want with it!" print "I also got other args:", args, kw f(self, *args, **kw) # ^ pass on self here return wrapper

或者

如果你想创建一个既可以用于类和方法的通用装饰器,你也可以这样做:

self

此外,当您需要将一些参数传递给装饰器时(例如def log_real_decorator(f): @wraps(f) def wrapper(*args, **kw): # Do something here f(*args, **kw) return wrapper ),使用您创建的装饰器。在您的情况下,您不需要它,而是您应该做的是如上所述,创建一个带有两个嵌套函数的装饰器,并将其称为@log_real_decorator(some_param=1)