Note: The syntax used in the below section is for Python 3. You may change it to use with a different version of Python.
Python Static Method
To Learn about OOPs Concepts – Read Python Class
What is a static method in Python?
It is available as a built-in function in Python and allows you to turn a regular method into the static.
In other words, you can create a callable class using the static method and use it with some restrictions.
It helps developers write code in a safe architectural way to prevent conflicts in the code.
How does the Python Static method work?
When you create a class, you usually define a few methods and properties. They may or may not have access to the class instance.
There three types of methods depending upon their access are Instance Method, Class Method, and Static Method. This tutorial will cover the application of Static Methods.
It is a method which does not have access to the class state. In other words, the method confines to itself and cannot change the properties of the class instance without any workaround.
You can make use of “staticmethod” in your programs with the following syntax:
class class_name: @staticmethod def object_behaviour: //Code to be executed
Alternatively, you can follow the below syntax:
Function returning a value as static:
Here is a simple program to demonstrate static methods.
class Math: @staticmethod def Multiply(one, two): return one * two math = Math() if(12*72 == math.Multiply(12, 72)): print("Equal") else: print("Not Equal")
Save the above code as “staticmethod.py” and execute. The output will come as:
A method as static:
Check another program to use the built-in staticmethod() function.
class Person: def Age(age): if(age <= 30): print("Young") elif(age>30 and age<=50): print("Middle Age") else: print("Senior Age") John = Person Type_of_age = staticmethod(John.Age(45))
Save the above code as “builtinstaticmethod.py” and execute. The output will come as: