0
0
Pythonprogramming~5 mins

Class methods and cls usage in Python

Choose your learning style9 modes available
Introduction

Class methods let you work with the class itself, not just one object. Using cls helps you change or use class-wide information easily.

When you want to create alternative ways to make objects.
When you need to change or check something that belongs to the whole class, not just one object.
When you want a method that works with the class but doesn't need a specific object.
When you want to keep track of how many objects of a class have been made.
Syntax
Python
class ClassName:
    @classmethod
    def method_name(cls, parameters):
        # code using cls to access class variables or methods

The @classmethod decorator marks the method as a class method.

cls is like self, but it points to the class, not an object.

Examples
This class method returns the species name shared by all dogs.
Python
class Dog:
    species = 'Canis familiaris'

    @classmethod
    def get_species(cls):
        return cls.species
This class method tells how many Dog objects have been created.
Python
class Dog:
    count = 0

    def __init__(self, name):
        self.name = name
        Dog.count += 1

    @classmethod
    def how_many(cls):
        return cls.count
This class method creates a Person object using birth year instead of age.
Python
class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age

    @classmethod
    def from_birth_year(cls, name, birth_year):
        current_year = 2024
        age = current_year - birth_year
        return cls(name, age)
Sample Program

This program shows how class methods can read and change a class variable shared by all objects. Changing wheels affects all cars.

Python
class Car:
    wheels = 4

    def __init__(self, brand):
        self.brand = brand

    @classmethod
    def number_of_wheels(cls):
        return cls.wheels

    @classmethod
    def change_wheels(cls, new_count):
        cls.wheels = new_count

# Check wheels before change
print(Car.number_of_wheels())

# Change wheels for all cars
Car.change_wheels(6)

# Check wheels after change
print(Car.number_of_wheels())

# Create a car and check wheels
my_car = Car('Toyota')
print(my_car.number_of_wheels())
OutputSuccess
Important Notes

Class methods can be called on the class itself or on an instance.

Using cls inside class methods helps keep code flexible if the class name changes.

Class methods cannot access instance variables directly because they don't get self.

Summary

Class methods work with the class, not individual objects.

cls is used inside class methods to refer to the class.

Use class methods to manage or change class-wide data or create alternative constructors.