Search code examples
pythonstatic-methods

Why is my subtract function working in a static context when I haven't used the @staticmethod decorator?


So, I did not know what static methods were so i searched it up and i made this

class Calculator:
    def __init__(self,num1,num2):
        self.num1 = num1
        self.num2 = num2

    @staticmethod
    def add(x,y):
        result = x + y
        return result

    def sub(x,y):
        result = x-y
        return result

print(Calculator.add(3,4))
print(Calculator.sub(5,7))

My question is why does the sub method works in a static context even without the @staticmethod decorator? Does it have something to do with the fact that the sub method doesn't use self.num1 or self.num2 or am I just implementing this wrong?


Solution

  • You don't see the difference because you didn't instantiate an object (Calculator is the class, Calculator() is an object).

    See the following snippet:

    class Calculator:
        @staticmethod
        def add(x,y):
            result = x + y
            return result
    
        def sub(x,y):
            result = x-y
            return result
    
    print(Calculator().add(3,4))
    print(Calculator().sub(5,7))
    

    The call to add will work, but not that to sub that will receive an extra first parameter.

    another example to illustrate your question in the comments:
    class Calculator:
        @staticmethod
        def add(x,y):
            result = x + y
            return result
        def sub(self,x,y):
            result = x-y
            return result
    
    print(Calculator().add(3,4))
    print(Calculator().sub(5,7))
    print(Calculator.sub(None,5,7))