Junior
How are static methods implemented in Python?
sobes.tech AI
Answer from AI
A static method is not bound to an instance of the class or the class itself. It behaves like a regular function but resides in the class's namespace.
It is implemented using the @staticmethod decorator.
class MyClass:
def __init__(self, value):
self.value = value
def instance_method(self):
# Instance method has access to self
print(f"Instance method: {self.value}")
@classmethod
def class_method(cls):
# Class method has access to the class via cls
print(f"Class method: {cls.__name__}")
@staticmethod
def static_method(x, y):
# Static method does not receive an implicit first argument (self or cls)
print(f"Static method: {x + y}")
# Calling the static method
MyClass.static_method(5, 10)
# It can also be called via an instance, but this is not recommended
obj = MyClass(20)
obj.static_method(1, 2)
Main characteristics:
- Does not accept an implicit first argument (
selforcls). - Does not have access to instance or class attributes.
- Resides in the class's namespace for logical grouping.
- Can be called via the class or an instance (though calling via the class is preferred).
The main purpose is utility functions related to the class but not dependent on the state of a specific instance or the class itself (e.g., helper functions, validators, generators that logically belong to the class).