Sobes.tech
Junior — Middle

Explain what it means to declare a method as static in object-oriented programming.

sobes.tech AI

Answer from AI

In object-oriented programming, a static method is a method that belongs to the class rather than an instance of the class. It is called directly through the class and does not have access to instance attributes or methods (self or this).

In Python, static methods are declared using the @staticmethod decorator. They are useful when a function is related to the class in a meaningful way but does not depend on the state of a specific object.

Example:

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

# Calling a static method without creating an instance
result = MathUtils.add(3, 5)
print(result)  # Outputs 8