Python classmethod() Method

Python classmethod() is a built-in method “used as a decorator to define a class method”. Class methods are bound to the class and not the instance of the object. As a result, they can be called on the class itself or any instance of the class. The first parameter of a class method is a reference to the class itself, which is usually named “cls”.

Example

class MainClass:
  main_var = 10

  @classmethod
  def main_class_method(cls):
    print("This is a class method.")
    print("The value of main_var is:", cls.main_var)


  # Call the class method on the class itself
  MainClass.main_class_method()

  # Create an instance of MainClass
  main_instance = MainClass()

  # Call the class method on the instance
  main_instance.main_class_method()

Output

This is a class method.
The value of main_var is: 10
This is a class method.
The value of main_var is: 10

In this code, the main_class_method() method is defined as a class method using the @classmethod decorator.

You can call this method on the class itself (MainClass.main_class_method()) or on any instance of the class (main_instance.main_class_method()).

The main advantage of class methods is that they can be overridden by subclasses.

This allows subclasses to provide a different implementation of the class method while still being able to call the original class method if needed.

 

 

 

 

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.