Search code examples
pythonclasserror-handlingstatic-methodspython-decorators

TypeError: 'staticmethod' object is not callable while using decorators inside classes


I have some code below

class Example:
    def __init__(self,height,weight)
        self.height = height
        self.weight = weight

    @staticmethod
    def some_op(func)
        def inner(*args,**kwargs)
        s = func(*args,**kwargs)
        print("Implementing function...")


    @some_op
    def num_op(self,values):
        for value in values:
            v = value * 10
            q = v - 100
            c = q ** -1
        return c

example = Example()

values = [11,23123,1209,234]

example.num_op(values)

But it outputs:

TypeError: 'staticmethod' object is not callable

I don't really know decorators inside a class, so how should I change the code so that it returns:

Implementing function...
0.0004464285714285714

Thank you very much!


Solution

  • A static method isn't callable; it's an object whose __get__ method returns a callable object. However, you aren't accessing some_op (incomplete definition aside) as an attribute, but as a regular function, so its __get__ method never gets used. You have two options:

    1. Define some_op as a regular function outside the class.
    2. Don't define some_op as a static method. Since you are only calling it inside the class definition itself, let it be a regular function, and just don't use it as an instance method. (You can define it as _some_op to emphasize that it shouldn't be used outside the class.)

    For more information on what __get__ is and how it works, see the Decriptor HowTo Guide and the section on static methods in particular.