2

I'm trying to decorate class method using class-decorator. For example

class MyDecorator(object):
    def __init__(self,param1):
        self.param1 = param1
        # do some action with param1

    def __call__(self,func):
        def wrapped(*args,**kwargs):
             print "in wrapper:"
             func(*args,**kwargs)

        return wrapped

and my some class:

class A:
    @MyDecorator("Blablabla")
    def func1(arg1,arg2,arg3):
         print (arg1,arg2,arg3)

but when I do the next action:

a = A()
a.func(1,2,3)

I get the following error:

TypeError: func1() takes exactly 3 arguments (4 given)
martineau
  • 119,623
  • 25
  • 170
  • 301
kostyll
  • 41
  • 4

2 Answers2

2
class A:
    @MyDecorator("Blablabla")
    def func1(self, arg1, arg2, arg3):
        print (arg1,arg2,arg3)

You need to add the self argument to your function.

Andrew Sledge
  • 10,163
  • 2
  • 29
  • 30
1

If you prefer to write your func1 method without a first self argument, you need to drop this argument in the decorator:

def __call__(self, func):
    def wrapped(obj, *args, **kwargs):
         # obj is just ignored
         print "in wrapper:"
         func(*args, **kwargs)

This is quite the same as using @staticmethod: when calling a.func1, a is passed as first argument, but this argument is removed by the decorator.

Nicolas Cortot
  • 6,591
  • 34
  • 44
  • This is true, but that's not what is causing the error that OP is getting. – Andrew Sledge Dec 26 '13 at 16:00
  • @AndrewSledge Both solutions are valid and fix the OP's error, although with yours the code will certainly be easier to read. Mine is only useul if you need to implement `@staticmethod` behaviour. – Nicolas Cortot Dec 26 '13 at 16:12