@staticmethodmean in Python, and how are they different? When should I use them, why should I use them, and how should I use them?
As far as I understand,
@classmethodtells 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
staticmethodare quite similar, there’s a slight difference in usage for both entities:
classmethodmust have a reference to a class object as the first parameter, whereas
staticmethodcan have no parameters at all.
Here we have
__init__, a typical initializer of Python class instances, which receives arguments as a typical instance method, having the first non-optional argument (
self) that holds a reference to a newly created instance.
We have some tasks that can be nicely done using
Let’s assume that we want to create a lot of
Dateclass 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:
- Parse a string to receive day, month and year as three integer variables or a 3-item tuple consisting of that variable.
Dateby passing those values to the initialization call.
This will look like:
classmethod. Let’s create another constructor.
- We’ve implemented date string parsing in one place and it’s reusable now.
- Encapsulation works fine here (if you think that you could implement string parsing as a single function elsewhere, this solution fits the OOP paradigm far better).
clsis the class itself, not an instance of the class. It’s pretty cool because if we inherit our
Dateclass, all children will have
staticmethod? It’s pretty similar to
classmethodbut 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
Dateclass we’ve used so far, but doesn’t require instantiation of it.
Here is where
staticmethodcan be useful. Let’s look at the next piece of code:
day, month, year = map(int, date_as_string.split(‘-‘))
return day <= 31 and month <= 12 and year <= 3999 # usage: is_date = Date.is_date_valid('11-09-2012') [/code]
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 other methods), which
If you have better answer, please add a comment about this, thank you!