简体   繁体   English

Python 将 self 传递给装饰器

[英]Python passing self to the decorator

I'm trying to pass the self object to my decorator to access its contents but get the following error:我试图将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()

Error:-错误:-

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

This is how you do it:这是你如何做到的:

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

Simply pass on self .简单地传递self

Or或者

If you want to create a generic decorator that can both be used for class and methods you can simply do this:如果你想创建一个可以同时用于类和方法的通用装饰器,你可以简单地这样做:

def log_real_decorator(f):
    @wraps(f)
    def wrapper(*args, **kw):
        # Do something here
        f(*args, **kw)

    return wrapper

Also, the decorator that you have created is used when you need to pass some parameters to the decorator(like @log_real_decorator(some_param=1) . In your case, you don't need that, instead what you should do is create a decorator with two nested functions as I have done above and call it as @log_real_decorator .此外,当您需要将一些参数传递给装饰器时,将使用您创建的装饰器(例如@log_real_decorator(some_param=1) 。在您的情况下,您不需要它,而是您应该做的是创建一个装饰器有两个嵌套函数,就像我在上面所做的那样,并将其称为@log_real_decorator

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM