How to Use Class Methods

Published Aug. 29, 2023, 1:33 a.m.

How to Use Class Methods: Working with Data that Belongs to the Class

In Python classes, we can use a special type of method called a class method to work with data that belongs to the class, not to any specific object. This data is called class variable or static variable, and it is shared by all the objects of the class.

How to Make a Class Method:

A class method is marked with the @classmethod sign above it. Inside this method, we use a special word called cls, which means the class itself. This word lets us use and change the class variable.

How it Looks:

class ClassName:
    @classmethod
    def methodName(cls, ...):
        # What the method does

Example: Counting How Many Objects We Made

Let's say we want to know how many objects of a class we have made. We can use a class method to do this. Let's see how it works with a class called Animal.

class Animal:
    total_animals = 0  # Class variable to count how many animals we have
    
    def __init__(self, name, legs):
        self.name = name
        self.legs = legs
        Animal.total_animals += 1  # Add one to the count when we make an animal
    
    @classmethod
    def display_total(cls):
        print("Total animals:", cls.total_animals)

# Making animal objects
cat = Animal("Cat", 4)
dog = Animal("Dog", 4)
spider = Animal("Spider", 8)

# Calling the class method to show how many animals we have
Animal.display_total()

What We See:

Total animals: 3

What It Means:

  1. The Animal class has a class variable total_animals that starts with 0.
  2. The __init__ method (the one that makes objects) adds one to total_animals every time we make an animal.
  3. The display_total class method shows us how many animals we have made.
  4. We make three animals: catdog, and spider.
  5. We call the display_total class method using the class name, and it tells us we have three animals.

In Short:

Class methods let us work with data that belongs to the class, not to any specific object. They help us keep track of what is happening in the class and make sure all the objects follow the same rules. The example above shows how class methods can be used to count and show how many objects we have made.