You are currently viewing Static Methods in Python Explained

Static methods in Python are a type of method that are used to define functions that belong to a class rather than an instance of a class. To create a static method in python, we use the @staticmethod decorator. In this article, you will learn static methods in Python, along with use cases and examples.

Advertisements

1. What is a Static Method?

In Python, we can define a regular function that performs a specific task. However, when we are working with object-oriented programming, we might need to associate a function to a class instead of the instances. In that case, we feel the need for a static method.

Generally, static methods are used in object-oriented programming to associate a function with a class rather than with an instance of the class. A static method is a method that can be called on the class itself, rather than on an instance of the class.


# Class with static method
class MyClass:
    @staticmethod
    def my_func():
        print("Static method.")

# Call static method
MyClass.my_func()

When we define a function that belongs to a class, we have the option to define it as a static method. These methods might be needed in your program if you want to create a utility function in your class.

2. Create Static Method in Python

Creating a static method in Python is quite simple. To define a static method, we use the @staticmethod decorator before the method definition. The @staticmethod decorator tells Python that the method should be treated as a static method, rather than an instance method or a class method.

2.1 Syntax

The syntax of static method in python looks like this:


# Syntax to create static method
class MyClass:
    @staticmethod
    def my_static_method():
        pass

2.2 Static Method Example

Suppose you have a Python script that needs to perform some common file operations, such as copying files, deleting files, or renaming files. You can create a file utility class with static methods that can perform these operations.


# Import os module
import os

# Create class with 2 static methods
class FileUtils:

    @staticmethod
    def delete_file(filename):
        os.remove(filename)

    @staticmethod
    def rename_file(oldname, newname):
        os.rename(oldname, newname)

2.3 The staticmethod() Function

Beside the @staticmethod decorator, we can also use the staticmethod() function to create a static method. The staticmethod() function is called by passing a regular function as an argument and returns a static method object.


class MyClass:
    def my_method():
        print("This is a regular method")

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

# Using staticmethod() function
static_method = staticmethod(MyClass.my_method)

3. @staticmethod vs @classmethod Decorator

The @staticmethod decorator is used to define a static method inside a class. When a method is decorated with @staticmethod, it becomes a static method and can be called without an instance of the class.

Related: Python staticmethod vs classmethod Explained with Examples

@classmethod used for class methods inside a class. Static methods are similar to class methods, but there is one key difference. Class methods take the class itself as the first parameter (cls), while static methods do not take any special parameters.


# Create class with static & class methods
class MyClass:
    my_class_var = "This is a class variable"

    @staticmethod
    def my_static_method():
        print(f"This is a class method.")

    @classmethod
    def my_class_method(cls):
        print(f"This is a class method.")

# Calling the static method
MyClass.my_static_method()


# Calling the class method
obj = MyClass()
obj.my_class_method()

4. Usecase of Static Methods

Static methods are useful when you have a method that doesn’t depend on any instance or class variables, and you want to make it available to the class and its instances. Below are some use cases of static method.

4.1 Utility Functions

Sometimes, we have functions that we want to group together with a class, but they don’t depend on the state of the class or its instances. In this case, we can define them as static methods within the class.

See examples of math utils:


class MathUtils:
    @staticmethod
    def add(a, b):
        return a + b
    
    @staticmethod
    def subtract(a, b):
        return a - b
    
    @staticmethod
    def multiply(a, b):
        return a * b
    
    @staticmethod
    def divide(a, b):
        if b == 0:
            raise ValueError("Cannot divide by zero")
        return a / b

4.2 Building Cache

Let’s say we have a function that is expensive to compute, but its output doesn’t change very often. We can use a static method to cache the result of the function and avoid recomputing it every time the function is called with the same arguments.


class ExpensiveFunction:
    
    @staticmethod
    def compute(x, y):
        # Check if we've already computed this result
        key = f"{x},{y}"
        if key in ExpensiveFunction.cache:
            print(f"Returning cached value for {key}")
            return ExpensiveFunction.cache[key]
        
        # Compute the result
        result = x ** y
        
        # Store the result in the cache
        ExpensiveFunction.cache[key] = result
        return result
    
    cache = {}

5. Static methods Outside of Class in Python

Though python allows us to create a static method outside the class by using the staticmethod decorator, However, I didn’t find any use case. Defining static methods outside of classes is not a common practice and can be considered unorthodox in Python. So you should avoid it unless there is a specific case.


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

6. Summary and Conclusion

We have learned the concept of static methods in Python. Static methods provide a way to create utility functions that are related to a class but do not require access to instance variables. We can create static methods using the @staticmethod decorator or the staticmethod() function. I hope this article was helpful, please leave questions in the comment section.

Happy Coding!