While we believe that this content benefits our community, we have not yet thoroughly reviewed it. If you have any suggestions for improvements, please let us know by clicking the “report an issue“ button at the bottom of the tutorial.
In this quick post, we will learn how to create and use a Python static method. We will also have a look at what advantages and disadvantages static methods offer as compared to the instance methods. Let’s get started.
Static methods in Python are extremely similar to python class level methods, the difference being that a static method is bound to a class rather than the objects for that class. This means that a static method can be called without an object for that class. This also means that static methods cannot modify the state of an object as they are not bound to it. Let’s see how we can create static methods in Python.
Python Static methods can be created in two ways. Let’s see each of the ways here:
Let’s directly jump to sample code snippet on how to use the
class Calculator: def addNumbers(x, y): return x + y # create addNumbers static method Calculator.addNumbers = staticmethod(Calculator.addNumbers) print('Product:', Calculator.addNumbers(15, 110))
Note that we called the addNumbers we created without an object. When we run this program, here is the output we will get: There were no surprises there. This approach is controlled as at each place, it is possible to create a static method out of a class method as well. Let’s see another approach with the same example here.
This is a more subtle way of creating a Static method as we do not have to rely on a statement definition of a method being a class method and making it static at each place you make it static. Let’s use this annotation in a code snippet:
class Calculator: # create addNumbers static method @staticmethod def addNumbers(x, y): return x + y print('Product:', Calculator.addNumbers(15, 110))
When we run this program, here is the output we will get: This was actually a much better way to create a static method as the intention of keeping the method static is clear as soon as we create it and mark it with the
Static methods have a very clear use-case. When we need some functionality not w.r.t an Object but w.r.t the complete class, we make a method static. This is pretty much advantageous when we need to create Utility methods as they aren’t tied to an object lifecycle usually. Finally, note that in a static method, we don’t need the
self to be passed as the first argument. API Reference: Python Documentation
Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.