Static Method in Python with Example

A method defined with an @staticmethod decorator in a class is called static method in Python. Similar to the class method, this method also belongs to a class rather than an instance of the class.

Since a static method does not depend on any specific instance of the class, therefore, we can call it without creating any object of that class. A static method is called on the class itself, but not on an object of the class.

This method is like a class method with one difference. We cannot access class variable (or class specific data) inside it.

We often use static methods for utility functions that are related to the class but do not require access to instance-specific data. Let’s understand the basic syntax to define a static method in a class.

Syntax to Define Static Method in Python


To define a static method, we’ll need to use the @staticmethod decorator followed by a method definition within the class. The general syntax to define a static method inside a class is as follows:

class MyClass:
    @staticmethod
    def static_method_name(parameter1, parameter2, ...):
        # Method body
        # Static method logic here.

In the above syntax,

(a) @staticmethod: A name used with (@) sign is called a decorator that indicates that the following method is a static method in Python.

(b) static_method_name: It is the name of static method which you can replace it with your desired name of static method.

(c) parameter1, parameter2, …: These are optional parameters that a static method header can accept. We can define any number of parameters as needed for our specific use. Basically, the parameters specify the input given to the method so that it can perform its task.

(d) Method body: It is the group of statements or code that the method executes to perform its tasks.


Note: A static method does not take the self or cls (short for class) references as a parameter because no instance is involved in it. It takes only arguments. If you add self parameter, it would be an instance method, not a static method. Similarly, if you use cls parameter, it would be a class method, not a static method.

Accessing Static Method in Python


A static method will execute when we call it. It is called on the class itself without creating any object of that class. To make a static method call, use the following syntax if a static method returns a value.

return_value = ClassName.static_method_name(arguments)

In the above syntax, the method returns a value, therefore, we will store it using a variable. If the static method does not return a value, use the below syntax:

className.static_method_name(arguments)

Here is simple examples:


Example 1:

class Student:
    @staticmethod
    def display():
        print("I am student.")

# Ouside the class definition.
# Call the static method using the name of class.
Student.display()

# We can also call the static method by creating an instamce of class.
obj = Student()
obj.display()
Output:
       I am student.
       I am student.

Example 2:

class MathOperations:
    @staticmethod
    def add(x, y):
        return x + y

    @staticmethod
    def subtract(x, y):
        return x - y

    @staticmethod
    def multiply(x, y):
        return x * y

    @staticmethod
    def divide(x, y):
        if y == 0:
            return "Cannot divide by zero"
        return x / y

# Outside the class definition.
# We can access and call static methods on the class itself, without creating an instance of the class.
result1 = MathOperations.add(5, 3)
result2 = MathOperations.subtract(10, 4)
result3 = MathOperations.multiply(6, 2)
result4 = MathOperations.divide(8, 2)

# Displaying the results.
print("Addition:", result1)
print("Subtraction:", result2)
print("Multiplication:", result3)
print("Division:", result4)
Output:
       Addition: 8
       Subtraction: 6
       Multiplication: 12
       Division: 4.0

In this example, we have defined a class named MathOperations with four static methods: add, subtract, multiply, and divide. We have called them directly on the class itself without creating any object of that class. We have stored the returned values into variables, result1, result2, and so on.

Can We Access Instance or Class Variables inside Static Method?


In Python, we can use instance variables and class variables (static variables) inside a static method, but we need to access them through the class itself or by passing an instance of the class as an argument to the static method. This is because static methods do not have access to instance specific data or attributes directly.


Look at the below example code how we can use instance and class variables in a static method.

Example 3:

# Python program to use the class variable inside a static method.
class MyClass:
    class_var = "I am a class variable"

    @staticmethod
    def static_method():
      # Calling a class variable using class name inside a static method.
        print(MyClass.class_var) 

# Calling the static method through the class
MyClass.static_method()
Output:
       I am a class variable

In this example, we have accessed the class variable class_variable inside the static_method() by using class name.

Example 4:

# Python program to use the instance variable inside a static method.
class MyClass:
    def __init__(self, instance_variable):
        self.instance_variable = instance_variable

    @staticmethod
    def static_method(instance):
        print(instance.instance_variable)

# Creating an instance of MyClass.
obj = MyClass("I am an instance variable")

# Calling the static method by passing an instance to the static method.
MyClass.static_method(obj)
Output:
       I am an instance variable

In this example, we have accessed an instance variable instance_variable inside the static_method() by passing an instance of MyClass as an argument to the method.

Can We Call Class Method inside Static Method?


Yes, we can call a class method inside a static method in Python. To do so, we would need to use the class name to access the class method, just like we call a regular function. Let’s take a simple example in which we will call a class method from within a static method.

Example 5:

# Python program to use the class method inside a static method.
class MyClass:
    class_var = "I am a class variable"

    @classmethod
    def class_method(cls):
        print("This is a class method")
        print(f"Accessing class variable: {cls.class_var}")

    @staticmethod
    def static_method():
        print("This is a static method")
        MyClass.class_method()  # Calling the class method

# Call the static method
MyClass.static_method()
Output:
       This is a static method
       This is a class method
       Accessing class variable: I am a class variable

Can We Call Instance Method inside Static Method?


Yes, we can call an instance method inside a static method in Python, but to do so, we need to create an instance of the class and then call the instance method on that instance.

Static methods do not have access to instance-specific data and also the self reference in the parameter because they are bound to the class, not bound to a specific instance. Here’s an example:

Example 6:

# Python program to use an instance method inside a static method.
class MyClass:
    def instance_method(self):
        print("This is an instance method")

    @staticmethod
    def static_method():
        print("This is a static method")
        instance = MyClass()  # Create an instance of the class
        instance.instance_method()  # Call the instance method

# Call the static method
MyClass.static_method()
Output:
       This is a static method
       This is an instance method

In this example, we have created a class MyClass with an instance method instance_method() and a static method static_method(). Inside the static_method(), we have created an instance of the class using MyClass(), and then called the instance_method() on that instance. When you run this code, it will produce the above output.

Can We Call Static Method inside Instance Method?


Yes, we can call a static method inside an instance or non-static method in Python. Actually, static methods are accessible from both instance methods and class methods. Here’s an example exhibiting how to call a static method from within an instance method:

Example 7:

# Python program to call static method inside a non-static method.
class MyClass:
    def instance_method(self):
        print("This is an instance method")
        self.call_static_method()

    @staticmethod
    def static_method():
        print("This is a static method")

    def call_static_method(self):
        print("Calling static method from instance method")
        MyClass.static_method()  # Call the static method

# Create an instance of the class
obj = MyClass()

# Call the instance method
obj.instance_method()
Output:
       This is an instance method
       Calling static method from instance method
       This is a static method

In this example, we have a class MyClass with an instance method instance_method(), a static method static_method(), and another instance method call_static_method(). Inside the instance_method, we called the call_static_method(), which, in turn, calls the static_method(). When we run this code, it will produce the above output.


Note: Avoid too many use of static methods because they may convert your code into the functional programming rather than object-oriented programming.

This is because static methods are simple regular functions which take everything from outside, just as independent or global functions. So, you should use less static methods if you prefer object-oriented programming.

Use of Static Method as Utility Functions


We mainly use static methods for utility functions that are related to the class, not for the instance-specific data attributes. Look at the below some example codes.

Example 8: Date Utility Class

from datetime import datetime
class DateUtils:
    @staticmethod
    def current_date():
        return datetime.now().date()

today = DateUtils.current_date()
print("Today's Date:", today)
Output:
       Today's Date: 2023-09-16

In this example, the DateUtils class has a static method current_date that returns the current date using the datetime module.

Example 9: File Utility Class

class FileUtils:
    @staticmethod
    def read_file(filename):
        try:
            with open(filename, 'r') as file:
                return file.read()
        except FileNotFoundError:
            return f"File '{filename}' not found."

content = FileUtils.read_file('sample.txt')
print("File Content:", content)
Output:
       File Content: File 'sample.txt' not found.

In this example, we have created a FileUtils class that contains a static method read_file() to read the content of a file specified by its filename.

Example 10: Math Constants

import math
class MathConstants:
    PI = math.pi

    @staticmethod
    def area_of_circle(radius):
        return MathConstants.PI * radius * radius

radius = 5
area = MathConstants.area_of_circle(radius)
print(f"Area of a circle with radius {radius} is {area}")
Output:
       Area of a circle with radius 5 is 78.53

In this example, we have created a MathConstants class that contains a static constant PI and a static method area_of_circle() that calculates the area of a circle using the constant.

Example 11: File Extension Checker

class FileExtensionChecker:
    @staticmethod
    def is_image_file(filename):
        image_extentions = ['.jpg', '.jpeg', '.png', '.gif', '.bmp']
        extension = filename.lower().split('.')[-1]
        return extension in image_extensions

filename = 'my_picture.jpg'
if FileExtensionChecker.is_image_file(filename):
    print(f"{filename} is an image file.")
else:
    print(f"{filename} is not an image file.")
Output:
       my_picture.jpg is not an image file.

In this example, we have created a FileExtensionChecker class that has a static method is_image_file() to check if a given filename represents an image file based on its extension.

Difference between Class Method and Static Method in Python


In Python, both class methods and static methods are associated with a class rather than with instances of the class. However, there are mainly two basic differences between class method and static method in Python. They are as:

Class Method:

  • To define a class method in a class, @classmethod decorator is used.
  • Class method takes cls (class) reference as the first parameter.

Static Method:

  • To define a static method in a class, @staticmethod decorator is used.
  • Static method does not take any reference parameter like cls or self.

In this tutorial, we have discussed static method in Python with a lot of example programs. Hope that you will have understood the basic syntax to define a static method inside the class and practiced all example programs.
Thanks for reading!!!

Please share your love