0

I know instance methods are useful when you need to do something with/to an instance of a class. I know that class methods are useful when you need a function that is relevant to the class, but not an instance itself. However a staticmethod fills the role when neither is needed. But why do they exist? Why can't every staticmethod be a classmethod

class A:

  @staticmethod
  def sum(a, b):
    return a + b

can always be written as

class A:

  @classmethod
  def sum(cls, a, b):
    return a + b

and they can be both invoked with A.sum(x, y).

Is a staticmethod more efficient? Or am I missing something.

EDIT:

Why I don’t believe the linked question answers my question. This is not about how staticmethods and classmethods differ, rather about the need for staticmethods to exist.

My understanding is that a staticmethod is just like a classmethod, except it doesn’t have access to the class. An analogy could be that a classmethod is like a car with brakes and a staticmethod is a car without brakes. You could use a car without brakes if you never need to brake, but the car with brakes can do the same job and more, so why does the one without brakes even exist?

rymanso
  • 869
  • 1
  • 9
  • 21
  • Not going to vote to reopen this but then short of is: static methods are used when they should be associated with the class but not necessarily an instance of the class. Constructors are a perfect example of a static method. You don't have an instance yet but you want one. Call a static method on the class to get an instance of it. – damccull Mar 30 '22 at 23:32
  • I guess a classmethod is inherited to child class, but staticmethod is only for the class you defined it in. Means **cls** will refer to parent in parent class and child in child class and this is not true for staticmethod. If you want something specific to a class use staticmethod. If inheritence is used, use classmethod. – Ranu Vijay May 03 '22 at 14:39

0 Answers0