Sobes.tech
Junior — Middle

How does the use of static methods differ from class methods in Python?

sobes.tech AI

Answer from AI

A static method in Python is a method that does not automatically take an instance of the class (self) or the class itself (cls) as the first argument. It is declared using the @staticmethod decorator and behaves like a regular function, but logically belongs to the class.

A class method is declared with the @classmethod decorator and takes the class (cls) as the first argument. This allows the method to work with the class itself, for example, to create new instances or modify class properties.

Example:

class MyClass:
    @staticmethod
    def static_method():
        print("This is a static method")

    @classmethod
    def class_method(cls):
        print(f"This is a class method called for {cls}")

MyClass.static_method()  # Outputs: This is a static method
MyClass.class_method()   # Outputs: This is a class method called for <class '__main__.MyClass'>

Thus, use a static method when the function does not depend on the state of the class or its instances, and a class method when you need to work with the class itself.