0

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.

3 Answers3

1

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
chepner
  • 497,756
  • 71
  • 530
  • 681
1

Or you can put your decorator outside of the class

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

    return wrapper


class decoratortest:
    @dec
    def printer(self, a):
        print(a)

    def dectest(self):
        self.printer('hi')


x = decoratortest()
x.dectest()

Output:

hi
hi
bottledmind
  • 603
  • 3
  • 10
0
class decoratortest:
    def dec(func):
        def wrapper(self,*args,**kwargs):
            func(*args,**kwargs)
            func(*args,**kwargs)
        return wrapper

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

Added a default value for decorator when argument is not specified and it worked.

pedro_bb7
  • 1,601
  • 3
  • 12
  • 28