Notes

Static Method in Python [ English ]

< Prev Next >

1. Introduction

A static method in Python is a method that belongs to a class but does not depend on the class or its objects. It is used when a function is logically related to a class but does not need access to instance (self) or class (cls) data.

Static methods are defined using the @staticmethod decorator.

2. Definition

A static method is a method that:

3. Syntax

class ClassName:
    @staticmethod
    def method_name(parameters):
        # code

4. Basic Example

class MathOperations:
    
    @staticmethod
    def add(a, b):
        return a + b

print(MathOperations.add(5, 3))

Output

8

Explanation

5. Calling Static Method

Static methods can be called in two ways:

Using Class Name

MathOperations.add(2, 3)

Using Object

obj = MathOperations()
obj.add(2, 3)

6. Example with Utility Function

class Converter:

    @staticmethod
    def celsius_to_fahrenheit(c):
        return (c * 9/5) + 32

print(Converter.celsius_to_fahrenheit(25))

7. Key Difference: Instance vs Class vs Static Method

Feature Instance Method Class Method Static Method
First parameter self cls None
Access Instance variables Class variables No direct access
Decorator None @classmethod @staticmethod
Usage Object-specific logic Class-level logic Utility functions

8. When to Use Static Methods

Use static methods when:

9. Important Points

10. Example Comparing All Methods

class Example:

    def instance_method(self):
        print("Instance Method")

    @classmethod
    def class_method(cls):
        print("Class Method")

    @staticmethod
    def static_method():
        print("Static Method")

obj = Example()

obj.instance_method()
Example.class_method()
Example.static_method()

11. Summary

< Prev Next >