Published Aug. 29, 2023, 1:49 a.m.
How to Use Static Methods: Doing Things that Don't Need the Class or Object
In Python classes, we have a useful tool called a static method. These methods are for doing things that don't need any information from the class or the object. They are like helper functions that make our code better and simpler.
Static methods are good for when you need a function that is related to your class, but doesn't need to use or change any class or object variables. These methods are independent and don't need the self
or cls
words in their definition.
How it Looks:
class ClassName:
@staticmethod
def methodName(...):
# What the method does
Let's see how static methods work with a class called MathUtils
. We'll make three static methods: add
, product
, and average
.
class MathUtils:
@staticmethod
def add(x, y):
print('The Sum:', x + y)
@staticmethod
def product(x, y):
print('The Product:', x * y)
@staticmethod
def average(x, y):
print('The Average:', (x + y) / 2)
# Using static methods
MathUtils.add(10, 20)
MathUtils.product(10, 20)
MathUtils.average(10, 20)
The Sum: 30
The Product: 200
The Average: 15.0
MathUtils
class with three static methods: add
, product
, and average
.Static methods are simple and useful. They are good for making functions that have to do with the class's purpose but don't need any information from the class or the object. This helps us keep our code neat and organized. Static methods may not be used as often as other types of methods, but they are an important tool in your Python programming toolbox.