Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why use classmethod instead of staticmethod? [duplicate]

I know what they do and I've seen many examples of both, but I haven't found a single example where I would have to use classmethod instead of replacing it with a staticmethod.

The most common example of classmethod I've seen is for creating a new instance of the class itself, like this (very simplified example, there's no use of the method atm. but you get the idea):

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

This would return a new instance of Foo when calling foo = Foo.create_new(). Now why can't I just use this instead:

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

It does the exact same, why should I ever use a classmethod over a staticmethod?

like image 541
Patrik Lippojoki Avatar asked Apr 23 '13 14:04

Patrik Lippojoki


People also ask

Why should I use Classmethod?

If a classmethod is intended to operate on the class and a regular instance method is intended to operate on an instance of the class, then a classmethod is best used to for functionality associated with the class, but that would not be useful if applied to an existing instance of a class.

What is the difference between Classmethod and Staticmethod?

Class method can access and modify the class state. Static Method cannot access or modify the class state. The class method takes the class as parameter to know about the state of that class. Static methods do not know about class state.

What is the point of Classmethod Python?

A class method is a method which is bound to the class and not the object of the class. They have the access to the state of the class as it takes a class parameter that points to the class and not the object instance. It can modify a class state that would apply across all the instances of the class.

When should you use a Classmethod Python?

You can use class methods for any methods that are not bound to a specific instance but the class. In practice, you often use class methods for methods that create an instance of the class. When a method creates an instance of the class and returns it, the method is called a factory method.


1 Answers

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):     pass  obj = 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.

like image 139
Aya Avatar answered Oct 03 '22 03:10

Aya