Table of contents
1.
Introduction
2.
What is class methods in Python?
3.
Syntax for Class method in Python
4.
Parameters for Class Method in Python
5.
Return Values for Class Method in Python
6.
Exceptions for Class Method in Python
7.
Why Do We Use It?
8.
How to Use Class Method in Python ?
9.
Python @classmethod Decorator
9.1.
Syntax of @classmethod Decorator
9.2.
Python
10.
Class Method vs Static Method
10.1.
Example of @classmethod in Python
10.2.
Python
10.3.
Create Class Method Using @classmethod
10.4.
Python
11.
Factory Method Using a Class Method
11.1.
Python
12.
Frequently Asked Questions
12.1.
What is class methods in Python?
12.2.
What is __ call __ Classmethod in Python?
12.3.
When should I use Classmethod Python?
12.4.
What is the difference between @classmethod and @staticmethod in Python?
13.
Conclusion
Last Updated: Mar 27, 2024
Easy

Python Classmethod

Author Rinki Deka
0 upvote
Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

In Python, classes are the foundation of object-oriented programming. They encapsulate data and functions into a single entity. Within this encapsulation, Python provides different types of methods to interact with the class and its objects. One such method is the @classmethod. 

python classmethod

This article will explore the @classmethod in detail, providing clarity on its usage, syntax, and benefits through practical examples.

What is class methods in Python?

A @classmethod is a method that receives the class as an implicit first argument, rather than the instance of the class. This means it can be called on the class itself, rather than on an instance, to perform operations that are relevant to the class as a whole.

Syntax for Class method in Python

The syntax of a class method involves the @classmethod decorator, followed by a function definition that takes cls as the first parameter.

class MyClass:
    @classmethod
    def my_class_method(cls, arg1):
        # body of the method
        return

Also see, Python Operator Precedence

Parameters for Class Method in Python

  • The first parameter of a class method is conventionally named cls, representing the class itself. It is automatically passed by Python.
  • Additional parameters can be defined based on the specific requirements of the method.

Return Values for Class Method in Python

Class methods can return values like any other Python function. The return type is not explicitly declared, and it can be any valid Python data type.

Exceptions for Class Method in Python

Class methods can raise exceptions if an error occurs during their execution. Handling exceptions within the method or allowing them to propagate to the calling code depends on the specific requirements.

Why Do We Use It?

@classmethod is used when you need to perform a task that pertains to the class, but not necessarily to any individual instance of the class. It can access and modify class state that applies across all instances of the class.

How to Use Class Method in Python ?

To use a class method in Python, you need to define the class method using the @classmethod decorator and then call it on the class itself or an instance of the class. Here's a step-by-step guide:

1. Define the Class Method: Use the @classmethod decorator above the method definition. The first parameter is conventionally named cls and represents the class itself.

class MyClass:
   @classmethod
   def my_class_method(cls, param1, param2):
       # method implementation
       print(f"Class method called with {param1} and {param2}")

 

2. Call the Class Method on the Class: You can call the class method directly on the class, providing values for the parameters.

MyClass.my_class_method("value1", "value2")

 

3. Call the Class Method on an Instance: Alternatively, you can call the class method on an instance of the class.

my_instance = MyClass()
my_instance.my_class_method("value1", "value2")

Python @classmethod Decorator

The @classmethod decorator is used to define a method in the class that is bound to the class and not the instance of the class.

Syntax of @classmethod Decorator

  • Python

Python

class User:
active_users = 0
@classmethod
def display_active_users(cls):
return f"There are currently {cls.active_users} active users."

def __init__(self, name):
self.name = name
User.active_users += 1
def logout(self):
User.active_users -= 1
return f"{self.name} has logged out."

# Create users
user1 = User("John")
user2 = User("Marie")

# Display active users
print(User.display_active_users())
You can also try this code with Online Python Compiler
Run Code

 Output: 
 

output

In this example, display_active_users is a class method that returns the number of active users. When we create user1 and user2, the active_users class variable is incremented. The output reflects the current state of the class variable.

Class Method vs Static Method

A class method takes cls as the first parameter, while a static method doesn't take any implicit first argument (self or cls). Static methods know nothing about the class or instance state and are utility-type methods.

Example of @classmethod in Python

Create a Simple @classmethod

  • Python

Python

class Vehicle:
   base_sale_price = 0

   def __init__(self, wheels, miles):
       self.wheels = wheels
       self.miles = miles

   @classmethod
   def set_base_sale_price(cls, price):
       cls.base_sale_price = price

# Set base sale price for all instances of Vehicle
Vehicle.set_base_sale_price(15000)
You can also try this code with Online Python Compiler
Run Code

This class method sets a class variable that will be shared by all instances.

Create Class Method Using @classmethod

  • Python

Python

class Book:
TYPES = ('hardcover', 'paperback')

@classmethod
def types(cls):
return cls.TYPES

print(Book.types())
You can also try this code with Online Python Compiler
Run Code

Output: 

output

This method returns a class variable tuple containing different types of books.

Factory Method Using a Class Method

Factory methods are those that return an instance of the class.

  • Python

Python

class Rectangle:
   def __init__(self, width, height):
       self.width = width
       self.height = height

   @classmethod
   def square(cls, side_length):
       return cls(side_length, side_length)

# Create a square rectangle
square = Rectangle.square(5)
You can also try this code with Online Python Compiler
Run Code

Here, Rectangle.square(5) returns an instance of Rectangle with equal width and height, making it a square.

Frequently Asked Questions

What is class methods in Python?

Class methods in Python are defined using the @classmethod decorator. They have access to the class and can be called on the class or an instance.

What is __ call __ Classmethod in Python?

The __call__ method is one of Python's built-in methods, often referred to as dunder or magic methods due to the two underscores as prefixes and suffixes in their names. The primary purpose of the __call__ method is to enable a class to be invoked like a function, essentially allowing it to act as a callable object.

When should I use Classmethod Python?

Use class methods when the method needs access to the class itself, rather than the instance. Commonly used for alternative constructors or operations on the class.

What is the difference between @classmethod and @staticmethod in Python?

@classmethod has access to the class through the cls parameter, while @staticmethod does not. Class methods are aware of the class context, while static methods are not.

Conclusion

The @classmethod is a powerful tool in Python, allowing for operations that are relevant to the class as a whole rather than individual instances. It's particularly useful for factory methods and when you need to access or modify class state. With the examples provided, you should have a solid understanding of how to implement and use class methods in your Python programs.

You can refer to our guided paths on the Coding Ninjas. You can check our course to learn more about DSADBMSCompetitive ProgrammingPythonJavaJavaScript, etc. 

Also, check out some of the Guided Paths on topics such as Data Structure and AlgorithmsCompetitive ProgrammingOperating SystemsComputer Networks, DBMSSystem Design, etc., as well as some Contests, Test Series, and Interview Experiences curated by top Industry Experts.

Live masterclass