2

I have the below code which works fine if I remove self from methods

class tests:
    def __init__(self):
        pass
    def func(self,a):
        def wrapp(x):
            y=x+2
            return a(y)
        return wrapp
    @func
    def func1(self,b):
        return b

print (tests.func1(10))

I believe decorator function are functions that return another function. Will that not work inside class? Ignore the indentation error as I am not achievable when I paste the code here.. Please help me how I can achieve this scenario inside class..

Inder
  • 3,711
  • 9
  • 27
  • 42
DKS
  • 321
  • 1
  • 5
  • 9

2 Answers2

3

You can just declare your decorator outside of the class. Also, when you are decorating a class method, it seems you need to pass the self variable from the wrapper to the decorated function (changed the names for more clarity):

def add_two(fn):
    def wrapper(self, x):
        y = x + 2
        return fn(self, y) 
    return wrapper

class Test:
    @add_two
    def func1(self, b):
        return b

f = Test()
f.func1(5) # returns 7
solarc
  • 5,638
  • 2
  • 40
  • 51
1

This issue here isn't the decorator at all. This issue is you are using func1 and your decorator as static methods without removing the self argument. If you remove the self arguments this will work fine.

Without staticmethod decorator

class Test:
    def add_two(func=None):
        def wrapper_add_two(*args, **kwargs):
            return func(*args, **kwargs) + 2
        return wrapper_add_two

    @add_two
    def func1(b):
        return b

print(Test.func1(10)) #12

With staticmethod decorator

Unfortunately using them in this manner stores them as unbound static methods and you need to bind them for this to work properly.

class Test:
    @staticmethod
    def add_two(func):
        def wrapper_add_two(*args, **kwargs):
            return func.__func__(*args, **kwargs) + 2
        return wrapper_add_two

    @add_two.__func__
    @staticmethod
    def func1(b):
        return b

print(Test.func1(10)) #12

Running with the staticmethod decorator and without the function binding gives you

TypeError: 'staticmethod' object is not callable

pistolpete
  • 968
  • 10
  • 20
  • On Without Static Method decorator, Yes its work If I dont include self (thats what I mentioned in my query) In that case, its not necessary to have the function/method inside class. isnt it? – DKS Mar 21 '19 at 03:18
  • Look up what a static method is and that will answer your question. I think that is the big thing you are missing with this post, I'm not sure you understand what a static method is. – pistolpete Mar 21 '19 at 13:04