Search code examples
pythonoopstatic-methods

Is @staticmethod decorator needed for declaring a Static Method in Python?


I am curious about why we need the @staticmethod decorator to declare method as static.

I was reading about static methods in Python, and I came to know that a static method can be callable without instantiating its class.

So I tried the two examples below, but both do the same:

class StatMethod:
  def stat():
    print("without Decorator")

class StatMethod_with_decorator:
  @staticmethod
  def stat():
    print("With Decorator")

If I call the stat() method on the class directly, both print/show the values below:

>> StatMethod.stat()
without Decorator
>> StatMethod_with_decorator.stat()
With Decorator

Solution

  • You need the decorator if you intend to try to call the @staticmethod from the instance of the class instead of of the class directly

    class Foo():
        def bar(x):
            return x + 5
    
    >>> f = Foo()
    >>> f.bar(4)
    Traceback (most recent call last):
      File "<pyshell#7>", line 1, in <module>
        f.bar(4)
    TypeError: bar() takes 1 positional argument but 2 were given
    

    Now if I declare @staticmethod the self argument isn't passed implicitly as the first argument

    class Foo():
        @staticmethod
        def bar(x):
            return x + 5
    
    >>> f = Foo()
    >>> f.bar(4)
    9