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
?
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With