Static Method in Python. Topic – 46

Static Method in Python

Static Method in Python

A static method in python does not receive an implicit first argument. A static method is also a method that is bound to the class and not the object of the class. This method can’t access or modify the class state. It is present in a class because it makes sense for the method to be present in class.

Imagine a school with different classes like Science, Maths, and History. Each class has teachers with their own areas of expertise.

In the Science class, a teacher helps students conduct experiments. These experiments can vary for each student, but some basic principles remain the same across the board. These fundamental principles are what we call “static methods.”

Syntax Python Static Method:

Python
class C(object):
    @staticmethod
    def fun(arg1, arg2, ...):
        ...
returns: a static method for function fun.

When to use the class or static method?

We generally use the class method to create factory methods. Factory methods return class objects ( similar to a constructor ) for different use cases. We generally use static methods to create utility functions.

Python
class MyClass:
	def __init__(self, value):
		self.value = value

	@staticmethod
	def get_max_value(x, y):
		return max(x, y)

# Create an instance of MyClass
obj = MyClass(10)

print(MyClass.get_max_value(20, 30)) 

print(obj.get_max_value(20, 30)) 
Output
30
30

Let’s see another example:

Python
class MathHelper:
    """
    This class provides static methods for basic mathematical operations.
    """

    @staticmethod
    def add(x, y):
        """
        Adds two numbers and returns the sum.

        Args:
            x: The first number.
            y: The second number.

        Returns:
            The sum of x and y.
        """
        return x + y

    @staticmethod
    def subtract(x, y):
        """
        Subtracts two numbers and returns the difference.

        Args:
            x: The first number (minuend).
            y: The second number (subtrahend).

        Returns:
            The difference of x and y (x - y).
        """
        return x - y

# Create an object of MathHelper is not required for static methods
# math_helper = MathHelper()  # This would not cause any errors, but it's not necessary

# Use static methods directly with the class name
result_add = MathHelper.add(5, 3)
result_subtract = MathHelper.subtract(10, 2)

print(f"5 + 3 = {result_add}")  # Output: 5 + 3 = 8
print(f"10 - 2 = {result_subtract}")  # Output: 10 - 2 = 8
Output
5 + 3 = 8
10 - 2 = 8

Static Methods:

  • We define two methods, add and subtract, using the @staticmethod decorator. This decorator marks them as static methods.
  • Each method has a docstring explaining its functionality, arguments, and return value.
  • Static methods don’t receive a self parameter, unlike instance methods.
  • They perform calculations based on the provided arguments.

Object Creation (Not Required):

  • While you can create an object of MathHelper (math_helper = MathHelper()), it’s not necessary to use static methods.

Using Static Methods:

  • We call MathHelper.add(5, 3) and MathHelper.subtract(10, 2) directly using the class name.
  • The results are stored in variables result_add and result_subtract.

Printing Results:

  • We print the results using f-strings for formatted output.
Access Modifier in Python

Access Modifier in Python

let’s understand what an access modifier is. In programming languages, there are three ways to securely store data in…

I hope you understand “Static Method in Python. Need guidance or have questions? Drop a comment below. Share your email for a personalized touch—I’ll send exclusive resources and answer queries. Let’s code together, creating efficient code and memorable learning moments! 🚀

Finite number of  lines code and infinite possibilities

Programmer, Arpan Bera

Leave a Reply

Your email address will not be published. Required fields are marked *

ABOUT ME
Arpan Bera

Coding is like Love – everyone can start, but only a few finish without errors

Keep Updated to our News and Blog