Search code examples
pythonpython-decorators

Python decorators in classes with extra parameters


I read this

one answer and this another answer

but I'm not doing it right with parameters

class decoratortest:
    def dec(func):
        def wrapper(self,*args,**kwargs):
            func(*args,**kwargs)
            func(*args,**kwargs)
        return wrapper

    @dec
    def printer(self,a):
        print(a)
        
    def dectest(self):
        self.printer('hi')
x = decoratortest()
x.dectest()

I get the usual positional error argument. What's the right syntax so I can print hi twice?

For the future, this worked:

class decoratortest:
    def dec(func):
        def wrapper(self,*args,**kwargs):
            func(self,*args,**kwargs)
            func(self,*args,**kwargs)
        return wrapper

    @dec
    def printer(self,a):
        print(a)
        
    def dectest(self):
        self.printer('hi')
x = decoratortest()
x.dectest()

very tricky, you dont' type self in the decorator, but you do in the underlying wrapper and func items.


Solution

  • You have to pass self explicitly, since func is a reference to a regular function object, not the method object that self.printer produces (via the descriptor protocol):

    def dec(func):
        def wrapper(self, *args, **kwargs):
            func(self, *args, **kwargs)
            func(self, *args, **kwargs)
        return wrapper