A static method is used for utility functions that don't need to access instance or class data. It behaves like a regular function but lives inside the class for organization.
class Counter: count = 0 @classmethod def increment(cls): cls.count += 1 Counter.increment() Counter.increment() print(Counter.count)
The class method increment increases the class attribute count by 1 each time it is called. After two calls, count becomes 2.
class Person: def __init__(self, name): self.name = name def greet(self): return f"Hello, {self.name}!" p = Person('Alice') print(p.greet())
The instance method greet accesses the instance attribute name via self and returns a greeting with the actual name.
Class methods receive the class as the first argument and are commonly used as factory methods to create instances, possibly with different parameters or subclasses.
class Base: @staticmethod def static_method(): return 'Base static' @classmethod def class_method(cls): return f'{cls.__name__} class' def instance_method(self): return 'Base instance' class Child(Base): @staticmethod def static_method(): return 'Child static' @classmethod def class_method(cls): return f'{cls.__name__} class overridden' def instance_method(self): return 'Child instance' c = Child() print(c.static_method()) print(c.class_method()) print(c.instance_method())
The Child class overrides all three methods. Calling them on an instance of Child uses the overridden versions, so the output reflects the Child implementations.
