Sobes.tech
Junior

What is the @staticmethod decorator in Python?

sobes.tech AI

Answer from AI

@staticmethod is a built-in decorator in Python used to define a static method within a class.

A static method:

  • Does not take an implicit first argument (self or cls).
  • Has no access to instance or class attributes.
  • Behaves like a regular function but belongs to the class's namespace.

Main purposes:

  • Grouping logically related functions within a class.
  • Indicating that the method does not use instance or class data.

Advantages:

  • Improves code readability by showing that the method is independent of the object's state.
  • Avoids passing unnecessary arguments (self or cls).
  • Can slightly improve performance since it does not require looking up the method in the instance or class dictionary.

Example usage:

class MyClass:
    def __init__(self, value):
        self.value = value

    @staticmethod
    def greet():
        # Static method that does not require access to self or cls
        print("Hello from MyClass!")

    def instance_method(self):
        # Instance method that requires access to self
        print(f"Instance value: {self.value}")

# Calling static method via class
MyClass.greet()

# Calling static method via instance
obj = MyClass(10)
obj.greet()

# Calling instance method via instance
obj.instance_method()