Python - classmethod() Function



The Python classmethod() function converts an instance method to a class method. This function allows us to call a method inside the given class without creating its instance.

The classmethod() is an alternative to the @classmethod decorator that specifies a given method belongs to the class. It is often used for factory methods, which are methods that return an instance of the class.

The classmethod() function is one of the built-in functions and does not require any module to import.

Syntax

The syntax of Python classmethod() is shown below −

classmethod(instance_method)

Parameters

The Python classmethod() function accepts a single parameter −

  • instance_method − It represents an instance method.

Return Value

The Python classmethod() function returns a method that belongs to a class.

classmethod() Function Examples

Practice the following examples to understand the use of classmethod() function in Python:

Example: Create Factory Methods Using classmethod() Function

As mentioned earlier, the classmethod() can create factory methods that return class objects for different use cases. Here, we are creating two factory methods named "motorcycle()" and "car()" which are then used to create different types of vehicles.

class Vehicle:
   def __init__(self, wheels, seats):
      self.wheels = wheels
      self.seats = seats

def motorcycle(cls):
   return cls(2, 2)

def car(cls):
   return cls(4, 5)

# Converting instance method to class method
Vehicle.motorcycle = classmethod(motorcycle)
Vehicle.car = classmethod(car)

heroBike = Vehicle.motorcycle()
tataCar = Vehicle.car()
#printing the details
print("Bike details - ")
print(f"Wheels: {heroBike.wheels}, Seat Capacity: {heroBike.seats}")
print("Tata Car Details - ")
print(f"Wheels: {tataCar.wheels}, Seat Capacity: {tataCar.seats}") 

When we run the above program, it produces following result −

Bike details - 
Wheels: 2, Seat Capacity: 2
Tata Car Details - 
Wheels: 4, Seat Capacity: 5

Example: Modify Class State or Static Data

The @classmethod decorator can also be used to modify class state or static data. In this example, we define a variable and later modify its value using the decorator. This decorator is another way of specifying class method.

class Laptop:
   os = "windows"

   @classmethod
   def newOs(cls):
      cls.os = "iOS"

print(f"Previous operating system: {Laptop.os}")
# Changing the class attribute
Laptop.newOs()
print(f"New operating system: {Laptop.os}")  

Output of the above code is as follows −

Previous operating system: windows
New operating system: iOS
python_built_in_functions.htm
Advertisements