Introduction
In object-oriented programming, a class method is a method that is bound to the class and not the instance of the class. Class methods can modify class state that applies across all instances of the class. They are often used to create factory methods or modify class-level variables.
Class methods in Python are defined using the @classmethod decorator, and they take cls (which refers to the class itself) as their first parameter, rather than self (which refers to the instance of the class).
This tutorial will guide you through creating a Python program that demonstrates the use of a class method.
Example:
- Class:
Car - Class Method:
create_car_from_string() - Program Output:
Car: Toyota Corolla, Year: 2020
Problem Statement
Create a Python program that:
- Defines a class named
Carwith attributesbrand,model, andyear. - Implements a class method named
create_car_from_stringthat creates aCarobject from a string containing car details. - Demonstrates the use of the class method by creating an object using it and displaying the car’s details.
Solution Steps
- Define the
CarClass: Use theclasskeyword to define a class namedCar. - Add an Initialization Method: Define the
__init__method to initialize thebrand,model, andyearattributes. - Define the Class Method: Use the
@classmethoddecorator to define a class method namedcreate_car_from_string. - Create an Object Using the Class Method: Call the class method to create a
Carobject from a string. - Display the Car’s Details: Print the details of the created
Carobject.
Python Program
# Python Program to Create a Class Method
# Author: https://www.rameshfadatare.com/
# Step 1: Define the Car Class
class Car:
# Step 2: Add an Initialization Method
def __init__(self, brand, model, year):
self.brand = brand
self.model = model
self.year = year
# Step 3: Define the Class Method
@classmethod
def create_car_from_string(cls, car_string):
brand, model, year = car_string.split('-')
return cls(brand, model, int(year))
# Method to display car information
def display_info(self):
print(f"Car: {self.brand} {self.model}, Year: {self.year}")
# Step 4: Create an Object Using the Class Method
car_string = "Toyota-Corolla-2020"
my_car = Car.create_car_from_string(car_string)
# Step 5: Display the Car's Details
my_car.display_info()
Explanation
Step 1: Define the Car Class
- The
Carclass is defined using theclasskeyword. This class represents a car with specific attributes.
Step 2: Add an Initialization Method
- The
__init__method initializes thebrand,model, andyearattributes when a newCarobject is created. This method takesbrand,model, andyearas parameters.
Step 3: Define the Class Method
- The
create_car_from_stringclass method is defined using the@classmethoddecorator. This method takes a string in the format"brand-model-year"and splits it into components using thesplit('-')method. It then returns a newCarobject by callingcls(brand, model, int(year)), whereclsrefers to theCarclass.
Method to Display Car Information
- The
display_infomethod is defined to print the car’s details in a readable format.
Step 4: Create an Object Using the Class Method
- A string
car_stringcontaining car details is defined. Thecreate_car_from_stringclass method is then called to create aCarobject from this string.
Step 5: Display the Car’s Details
- The
display_infomethod is called on themy_carobject to print the details of the car.
Output Example
Example Output:
Car: Toyota Corolla, Year: 2020
Additional Examples
Example 1: Class Method to Track Number of Cars
class Car:
car_count = 0 # Class-level attribute
def __init__(self, brand, model, year):
self.brand = brand
self.model = model
self.year = year
Car.car_count += 1 # Increment car count for each new instance
@classmethod
def get_car_count(cls):
return cls.car_count
def display_info(self):
print(f"Car: {self.brand} {self.model}, Year: {self.year}")
# Create multiple car objects
car1 = Car("Toyota", "Corolla", 2020)
car2 = Car("Honda", "Civic", 2021)
# Display number of cars created
print(f"Number of cars created: {Car.get_car_count()}")
Output:
Number of cars created: 2
Example 2: Class Method for Alternative Object Creation
class Rectangle:
def __init__(self, width, height):
self.width = width
self.height = height
@classmethod
def create_square(cls, side_length):
return cls(side_length, side_length)
def area(self):
return self.width * self.height
# Create a square using the class method
square = Rectangle.create_square(5)
print(f"Square area: {square.area()}")
Output:
Square area: 25
Example 3: Using Class Method to Modify Class-Level Data
class Employee:
raise_amount = 1.05 # Class-level attribute
def __init__(self, name, salary):
self.name = name
self.salary = salary
def apply_raise(self):
self.salary *= self.raise_amount
@classmethod
def set_raise_amount(cls, amount):
cls.raise_amount = amount
# Modify the class-level raise_amount using class method
Employee.set_raise_amount(1.10)
# Create an employee and apply raise
emp = Employee("John", 50000)
emp.apply_raise()
print(f"{emp.name}'s salary after raise: {emp.salary}")
Output:
John's salary after raise: 55000.0
Conclusion
This Python program demonstrates how to create and use a class method, which is a method bound to the class rather than an instance. Class methods are useful for tasks like creating factory methods, modifying class-level data, and providing alternative constructors. Understanding how to implement and use class methods is essential for writing clean, maintainable, and flexible object-oriented Python code.