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?