Python Class Methods: Understanding and Creating Class Methods

Explore Python class methods, which are bound to the class rather than instances. Learn how to create class methods using the classmethod() function and the @classmethod decorator, and understand their differences from static and instance methods.



Python - Class Methods

Methods belong to an object of a class and are used to perform specific operations. There are three categories of Python methods: class methods, instance methods, and static methods.

Class Method

A class method is bound to the class and not to an instance of the class. It can be called on the class itself. Unlike class methods, static methods do not have access to the cls parameter and cannot modify the class state. Instance methods can access both instance variables and class variables.

Creating Class Methods

There are two ways to create class methods in Python:

  • Using classmethod() Function
  • Using @classmethod Decorator

Using classmethod() Function

The classmethod() function transforms an instance method into a class method.

Syntax

      classmethod(instance_method)
              
Example

      class Employee:
         empCount = 0
         def __init__(self, name, age):
            self.__name = name
            self.__age = age
            Employee.empCount += 1
         def showcount(self):
            print(self.empCount)
            
         counter = classmethod(showcount)
      
      e1 = Employee("Aditi", 24)
      e2 = Employee("Vikram", 26)
      e3 = Employee("Sara", 27)
      
      e1.showcount()
      Employee.counter()
              
Output

      3
      3
              

Using @classmethod Decorator

The @classmethod decorator is the preferred way to define a class method.

Syntax

      @classmethod
      def method_name():
         # your code
              
Example

      class Employee:
          empCount = 0
          def __init__(self, name, age):
              self.name = name
              self.age = age
              Employee.empCount += 1
      
          @classmethod
          def showcount(cls):
              print(cls.empCount)
      
          @classmethod
          def newemployee(cls, name, age):
              return cls(name, age)
      
      e1 = Employee("Aditi", 24)
      e2 = Employee("Vikram", 26)
      e3 = Employee("Sara", 27)
      e4 = Employee.newemployee("Anil", 21)
      
      Employee.showcount()
              
Output

      4
              

Access Class Attributes in Class Method

To access class attributes within a class method, use the cls parameter followed by dot notation and the name of the attribute.

Example

      class Cloth:
         # Class attribute
         price = 4000
      
         @classmethod
         def showPrice(cls):
            return cls.price
      
      # Accessing class attribute
      print(Cloth.showPrice())
              
Output

      4000
              

Dynamically Add Class Method to a Class

The Python setattr() function is used to set an attribute dynamically.

Example

      class Cloth:
         pass
      
      # class method
      @classmethod
      def brandName(cls):
         print("Name of the brand is Raymond")
      
      # adding dynamically
      setattr(Cloth, "brand_name", brandName)
      newObj = Cloth()
      newObj.brand_name()
              
Output

      Name of the brand is Raymond
              

Dynamically Delete Class Methods

The Python del operator is used to delete a class method dynamically. Accessing the deleted method raises an AttributeError.

Example

      class Cloth:
         # class method
         @classmethod
         def brandName(cls):
            print("Name of the brand is Raymond")
      
      # deleting dynamically
      del Cloth.brandName
      print("Method deleted")
              
Output

      Method deleted