Could someone explain to me the meaning of @classmethod
and @staticmethod
in python? I need to know the difference and the meaning.
As far as I understand, @classmethod
tells a class that it's a method which should be inherited into subclasses, or... something. However, what's the point of that? Why not just define the class method without adding @classmethod
or @staticmethod
or any @
definitions?
tl;dr: when should I use them, why should I use them, and how should I use them?
I'm pretty advanced with C++, so using more advanced programming concepts shouldn't be a problem. Feel free giving me a corresponding C++ example if possible.
@classmethod
means: when this method is called, we pass the class as the first argument instead of the instance of that class (as we normally do with methods). This means you can use the class and its properties inside that method rather than a particular instance.@staticmethod
means: when this method is called, we don't pass an instance of the class to it (as we normally do with methods). This means you can put a function inside a class but you can't access the instance of that class (this is useful when your method does not use the instance).When to use each
@staticmethod
function is nothing more than a function defined inside a class. It is callable without instantiating the class first. It’s definition is immutable via inheritance.@classmethod
function also callable without instantiating the class, but its definition follows Sub class, not Parent class, via inheritance, can be overridden by subclass. That’s because the first argument for@classmethod
function must always becls (class)
.here is good link to this topic.
A slightly different way to think about it that might be useful for someone... A class method is used in a superclass to define how that method should behave when it's called by different child classes. A static method is used when we want to return the same thing regardless of the child class that we are calling.
Class method can modify the class state,it bound to the class and it contain cls as parameter.
Static method can not modify the class state,it bound to the class and it does't know class or instance
Though
classmethod
andstaticmethod
are quite similar, there's a slight difference in usage for both entities:classmethod
must have a reference to a class object as the first parameter, whereasstaticmethod
can have no parameters at all.Example
Explanation
Let's assume an example of a class, dealing with date information (this will be our boilerplate):
This class obviously could be used to store information about certain dates (without timezone information; let's assume all dates are presented in UTC).
Here we have
__init__
, a typical initializer of Python class instances, which receives arguments as a typicalinstancemethod
, having the first non-optional argument (self
) that holds a reference to a newly created instance.Class Method
We have some tasks that can be nicely done using
classmethod
s.Let's assume that we want to create a lot of
Date
class instances having date information coming from an outer source encoded as a string with format 'dd-mm-yyyy'. Suppose we have to do this in different places in the source code of our project.So what we must do here is:
Date
by passing those values to the initialization call.This will look like:
For this purpose, C++ can implement such a feature with overloading, but Python lacks this overloading. Instead, we can use
classmethod
. Let's create another "constructor".Let's look more carefully at the above implementation, and review what advantages we have here:
cls
is an object that holds the class itself, not an instance of the class. It's pretty cool because if we inherit ourDate
class, all children will havefrom_string
defined also.Static method
What about
staticmethod
? It's pretty similar toclassmethod
but doesn't take any obligatory parameters (like a class method or instance method does).Let's look at the next use case.
We have a date string that we want to validate somehow. This task is also logically bound to the
Date
class we've used so far, but doesn't require instantiation of it.Here is where
staticmethod
can be useful. Let's look at the next piece of code:So, as we can see from usage of
staticmethod
, we don't have any access to what the class is---it's basically just a function, called syntactically like a method, but without access to the object and its internals (fields and another methods), while classmethod does.A little compilation
@staticmethod A way to write a method inside a class without reference to the object it is being called on. So no need to pass implicit argument like self or cls. It is written exactly the same how written outside the class, but it is not of no use in python because if you need to encapsulate a method inside a class since this method needs to be the part of that class @staticmethod is comes handy in that case.
@classmethod It is important when you want to write a factory method and by this custom attribute(s) can be attached in a class. This attribute(s) can be overridden in the inherited class.
A comparison between these two methods can be as below