Python Static Method
This article demonstrates how you can create and use static methods in Python.
Python Static Method
A static method belongs to a class; still, it’s not bound to the object of that class. Thus, it can be called without creating an instance of the class that it resides in. Since static methods aren’t bound to an object, it does not know about the properties of a class, so it can not access or modify the properties of the class.
Create and Use a Python Static Method
First, let’s create an instance method so we can differentiate it from a static method. Let’s say we have a class Coffee
with a method called is_hot
that accepts an integer as a parameter. It returns True
if the given integer is greater than 50 and False
if it is lesser than 50.
class Coffee:
def is_hot(self, temperature):
return temperature > 50
coffee = Coffee()
print(coffee.is_hot(100))
Output:
True
In the example above, coffee
, which is an instance of class Coffee
, was instantiated to be able to call the is_hot
method.
Now, let’s make is_hot
into a static method by using the @staticmethod
decorator. It’s a built-in decorator that is used to define a method as a static method.
class Coffee:
@staticmethod
def is_hot(temperature):
return temperature > 50
print(Coffee.is_hot(100))
Output:
True
Unlike the instance method that we created from the previous example, you don’t need to pass self
as a parameter for static methods, and you don’t need to create an instance of the class to be able to use a static method. You can simply use the process directly.
Alternatively, the staticmethod()
function can be used in creating a static method. This is a built-in function that takes a function as a parameter and returns it as a static method.
class Coffee:
def is_hot(temperature):
return temperature > 50
Coffee.is_hot = staticmethod(Coffee.is_hot)
print(Coffee.is_hot(100))
Output:
True
Static methods are useful when creating utility methods that do a task in isolation since it does not need to access or modify the properties of a class; it only works with the data passed in the arguments.
In summary, we can create a static method by using the @staticmethod
decorator or the staticmethod()
function. You don’t need to have an instance of a class to call a static method; we can simply call it directly.