Why use classmethod instead of staticmethod? [duplicate] Why use classmethod instead of staticmethod? [duplicate] python python

Why use classmethod instead of staticmethod? [duplicate]


There's little difference in your example, but suppose you created a subclass of Foo and called the create_new method on the subclass...

class Bar(Foo):    passobj = Bar.create_new()

...then this base class would cause a new Bar object to be created...

class Foo:    @classmethod    def create_new(cls):        return cls()

...whereas this base class would cause a new Foo object to be created...

class Foo:    @staticmethod    def create_new():        return Foo()

...so the choice would depend which behavior you want.


Yes, those two classes would do the same.

However, now imagine a subtype of that class:

class Bar (Foo):    pass

Now calling Bar.create_new does something different. For the static method, you get a Foo. For the class method, you get a Bar.

So the important difference is that a class method gets the type passed as a parameter.


From the docs, a class method receives its class as an implicit argument, while static methods are unaware of the class in which they reside.

This can be useful in situations where you have an inherited static method that you want to override with different behaviour in the subclass.