Python将self传递给装饰器

问题描述 投票:0回答:1

我正在尝试将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)
python python-decorators
1个回答
5
投票

这是你如何做到的:

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)。在你的情况下,你不需要它,而你应该做的是创建一个带有两个嵌套函数的装饰器,因为我已完成上述并将其称为@log_real_decorator

© www.soinside.com 2019 - 2024. All rights reserved.