Movatterモバイル変換


[0]ホーム

URL:


Python Tutorial

Python - classmethod() Function



ThePython 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.

Theclassmethod() is an alternative to the@classmethoddecorator 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.

Theclassmethod() function is one of thebuilt-in functions and does not require any module to import.

Syntax

The syntax of Pythonclassmethod() is shown below −

classmethod(instance_method)

Parameters

The Pythonclassmethod() function accepts a single parameter −

  • instance_method − It represents an instance method.

Return Value

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

classmethod() Function Examples

Practice the following examples to understand the use ofclassmethod() 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 = seatsdef motorcycle(cls):   return cls(2, 2)def car(cls):   return cls(4, 5)# Converting instance method to class methodVehicle.motorcycle = classmethod(motorcycle)Vehicle.car = classmethod(car)heroBike = Vehicle.motorcycle()tataCar = Vehicle.car()#printing the detailsprint("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: 2Tata 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 attributeLaptop.newOs()print(f"New operating system: {Laptop.os}")

Output of the above code is as follows −

Previous operating system: windowsNew operating system: iOS
python_built_in_functions.htm
Print Page
Advertisements

[8]ページ先頭

©2009-2025 Movatter.jp