How to Use Static Methods

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.

What are Static Methods?

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

Example: Doing Math

Let's see how static methods work with a class called MathUtils. We'll make three static methods: addproduct, 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)

What We See:

The Sum: 30
The Product: 200
The Average: 15.0

What It Means:

  1. We make the MathUtils class with three static methods: addproduct, and average.
  2. Static methods are used with the class name, as shown in the example.
  3. We use the static methods to do the math and show the answers.

In Short:

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.