Skip to content
TheChatArchiveThe Chat Archive
gpt-4o-2024-08-06· OpenAIAi2 WildChat-4.8M (AI2)

What’s the difference between static method and class method in python

  1. User

    What’s the difference between static method and class method in python

  2. Assistant

    In Python, both static methods and class methods are types of methods that can be defined within a class, but they serve different purposes and have distinct characteristics.

    Static Method:

    • Definition: A static method is defined using the @staticmethod decorator.
    • Binding: It does not receive an implicit first argument. In other words, it does not have access to the instance (self) or class (cls) it is defined within.
    • Use Case: Static methods are used to define utility functions that have a logical connection with the class they are defined in but do not require access to the class or instance attributes.
    • Access: They can be called on an instance or directly on the class, as they do not depend on instance or class data.

    Example:

    class MathOperations:
        @staticmethod
        def add(x, y):
            return x + y
    
    # Usage
    result = MathOperations.add(5, 7)  # Calls the static method directly
    

    Class Method:

    • Definition: A class method is defined using the @classmethod decorator.
    • Binding: It takes cls as its first parameter, which represents the class itself, not the instance. This means it can access and modify class state that applies across all instances.
    • Use Case: Class methods are often used for factory methods that instantiate an instance using an alternative constructor or for methods that need to modify class-level data.
    • Access: Like static methods, class methods can be called on an instance or directly on the class.

    Example:

    class MyClass:
        class_variable = 0
        
        @classmethod
        def set_class_variable(cls, value):
            cls.class_variable = value
    
    # Usage
    MyClass.set_class_variable(10)  # Modifies the class variable
    print(MyClass.class_variable)
    

    Key Differences:

    1. Parameter: Static methods do not take cls or self as parameters, while class methods require cls.
    2. Purpose: Static methods are utility functions related to a class, whereas class methods are intended to modify class state.
    3. Access: Static methods do not modify object or class state, whereas class methods can modify class state.