static method
In Python, a static method is a method that belongs to a class but doesn’t operate on an instance or the class itself.
You define a static method using the @staticmethod
decorator. Static methods don’t receive an implicit self
or cls
argument. This means they can’t access or modify instance attributes or class attributes. The Python runtime enforces this behavior by not passing the instance or class object as an argument.
You often use static methods for utility functions that logically belong to a class but don’t require access to any instance or class-level data. They help organize code by keeping related functionality within a class.
Example
Here’s an example of using static methods:
calculations.py
class Calculator:
@staticmethod
def add(a, b):
"""Returns the sum of two numbers."""
return a + b
@staticmethod
def subtract(a, b):
"""Returns the difference between two numbers."""
return a - b
# Calling a static method on the class
print(Calculator.add(5, 7)) # Output: 12
# Calling a static method on an instance
calculator = Calculator()
print(calculator.subtract(5, 7)) # Output: -2
In this example, .add()
and .subtract()
are static methods that perform addition and subtraction, respectively. You can call them directly on the Calculator
class or on an instance of the class without affecting instance or class state.
Related Resources
Tutorial
Python's Instance, Class, and Static Methods Demystified
This tutorial helps demystify what's behind class, static, and instance methods in Python.
For additional information on related topics, take a look at the following resources:
- Object-Oriented Programming (OOP) in Python (Tutorial)
- Python Classes: The Power of Object-Oriented Programming (Tutorial)
- OOP Method Types in Python: @classmethod vs @staticmethod vs Instance Methods (Course)
- Intro to Object-Oriented Programming (OOP) in Python (Course)
- Object-Oriented Programming (OOP) in Python (Quiz)
- Class Concepts: Object-Oriented Programming in Python (Course)
- Inheritance and Internals: Object-Oriented Programming in Python (Course)
- Python Classes - The Power of Object-Oriented Programming (Quiz)