skip to Main Content

@staticmethod vs @classmethod in Python

In Python, both @staticmethod and @classmethod decorators are used to define methods within a class that are independent of the instance state. However, there are some differences between the two.

@staticmethod:

  • A static method is defined using the @staticmethod decorator.
  • It is bound to the class rather than the instance and does not have access to the instance or its attributes.
  • Static methods can be called on the class itself without creating an instance of the class.
  • They are commonly used for utility functions or methods that do not require access to the instance or its state.
  • Static methods do not implicitly pass any parameters (e.g., self or cls).
  • Example usage:
    class MyClass:
        @staticmethod
        def my_static_method():
            # implementation
    
    MyClass.my_static_method()  # Call the static method directly on the class
    

@classmethod:

  • A class method is defined using the @classmethod decorator.
  • It receives the class itself (cls) as the first parameter, allowing access to class-level attributes and methods.
  • Class methods can also access and modify the instance state if necessary.
  • They can be called on both the class and its instances.
  • Class methods are often used as alternative constructors or to modify class-level attributes.
  • Class methods are typically defined with the cls parameter convention, but any other name can be used.
  • Example usage:
    class MyClass:
        class_attribute = 42
    
        @classmethod
        def my_class_method(cls):
            # Access class attributes and methods using cls
            print(cls.class_attribute)
    
    MyClass.my_class_method()  # Call the class method on the class
    instance = MyClass()
    instance.my_class_method()  # Call the class method on an instance
    

In summary, @staticmethod is used for methods that do not require access to instance or class state, while @classmethod allows access to class-level attributes and methods through the cls parameter. Both decorators serve different purposes and can be used depending on the specific requirements of your code.

A Self Motivated Web Developer Who Loves To Play With Codes...

This Post Has 0 Comments

Leave a Reply

Your email address will not be published. Required fields are marked *

Back To Top