Now, we are going to learn about Python Static Methods. Basically, if we have a look at variables, we have the instance variables, which are for the instance, and the class variables, which are for the class. But here in the methods, we have the instance methods, and class methods, and there are static methods as well.
We have the instance methods, to access and change the object state. On the other hand, we have the class methods, to access or change the class status. Then we have the static methods, which can neither change the class status, nor the object status.
So, the difference here is that when we are going to create the static methods, we are not going to pass any class or object reference. But we can pass any other arbitrary number of arguments. Also, it is bound to the class, and not to the object, so we can call it without the object reference, which means with the class name(or with the object reference as well)
Python Static Methods
Let’s have a look at a simple program, which would give an idea about how we can create static methods, and how we can use them. Basically, we are going to make use of the decorator @staticmethod, to flag the method as static.
As you can see in the above program, we have the static method here, and we made use of the @staticmethod decorator, to flag the method as static. We have created a method, which checks if the given number is even or not. The method is very simple, and also, we can see that we are not passing the class or object reference. However, we are passing the number, which we want to check if it is even or not. After that, you can see in the last instruction, we have called the isEven method, passing a number. If you try to execute the above program and observe the output, you can find that we get the output as – ‘The number is odd!’.
So, the thing is that with the static methods, we are not changing the state of either the class or the object. The static methods are restricted in what data they can access, and just they are part of the class.
There is one more way, to create a static method, using the built-in function staticmethod(), which returns a static method for the given function. Let’s have a look at a simple example, which tries to demonstrate the same thing.
As you can see in the above program, we have used the built – in staticmethod() function, which returns a static method for the given function. Again, we have the static method, and we are checking if the given number is even or odd.
Whenever we would want to create such methods, which would know nothing about the object, or the class, but would be doing something bound to that class, like some utility function for the class, in such a situation, we can create the static method.