The Wayback Machine - http://web.archive.org/web/20241103220442/https://www.geeksforgeeks.org/classmethod-in-python/
Open In App

classmethod() in Python

Last Updated : 05 Sep, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

The classmethod() is an inbuilt function in Python, which returns a class method for a given function. This means that classmethod() is a built-in Python function that transforms a regular method into a class method. When a method is defined using the @classmethod decorator (which internally calls classmethod()), the method is bound to the class and not to an instance of the class. As a result, the method receives the class (cls) as its first argument, rather than an instance (self).

classmethod() in Python Syntax

class MyClass:

@classmethod

def class_method(cls, *args, **kwargs):

# Method implementation

pass

Python classmethod() Function

In Python, the classmethod() function is used to define a method that is bound to the class and not the instance of the class. This means that it can be called on the class itself rather than on instances of the class. Class methods are useful when you need to work with the class itself rather than any particular instance of it.

Class Method vs Static Method

The basic difference between the class method vs Static method in Python and when to use the class method and static method in Python.

  • A class method takes class as the first parameter while a static method needs no specific parameters.
  • A class method can access or modify the class state while a static method can’t access or modify it.
  • In general, static methods know nothing about the class state. They are utility-type methods that take some parameters and work upon those parameters. On the other hand class methods must have class as a parameter.
  • We use @classmethod decorator in Python to create a class method and we use @staticmethod decorator to create a static method in Python.

Example of classmethod in Python

Create a simple classmethod

In this example, we are going to see how to create a class method in Python. For this, we created a class named “Geeks” with a member variable “course” and created a function named “purchase” which prints the object. Now, we passed the method Geeks.purchase into a class method using the @classmethod decorator, which converts the method to a class method. With the class method in place, we can call the function “purchase” without creating a function object, directly using the class name “Geeks.”

Example of Class Method:

Python
class Geeks:
    course = 'DSA'
    list_of_instances = []

    def __init__(self, name):
        self.name = name
        Geeks.list_of_instances.append(self)

    @classmethod
    def get_course(cls):
        return f"Course: {cls.course}"

    @classmethod
    def get_instance_count(cls):
        return f"Number of instances: {len(cls.list_of_instances)}"

    @staticmethod
    def welcome_message():
        return "Welcome to Geeks for Geeks!"

# Creating instances
g1 = Geeks('Alice')
g2 = Geeks('Bob')

# Calling class methods
print(Geeks.get_course())  
print(Geeks.get_instance_count())  

# Calling static method
print(Geeks.welcome_message())  

Output

Course: DSA
Number of instances: 2
Welcome to Geeks for Geeks!

Create class method using classmethod()

Created print_name classmethod before creating this line print_name() It can be called only with an object not with the class now this method can be called as classmethod print_name() method is called a class method.

Python
class Student:

    # create a variable
    name = "Geeksforgeeks"

    # create a function
    def print_name(obj):
        print("The name is : ", obj.name)


# create print_name classmethod
# before creating this line print_name()
# It can be called only with object not with class
Student.print_name = classmethod(Student.print_name)

# now this method can be called as classmethod
# print_name() method is called a class method
Student.print_name()

Output
The name is :  Geeksforgeeks

Factory method using a Class Method

A common use case for class methods is defining factory methods. Factory methods are methods that return an instance of the class, often using different input parameters.

Python
class Date:
    def __init__(self, year, month, day):
        self.year = year
        self.month = month
        self.day = day

    @classmethod
    def from_string(cls, date_string):
        year, month, day = map(int, date_string.split('-'))
        return cls(year, month, day)

Here, from_string is a factory method that creates an instance of the Date class from a string:

Python
date = Date.from_string('2023-07-16')
print(date.year, date.month, date.day)  

Output

2023 7 16

How the class method works for the inheritance?

In this example, we are making Python class hierarchy with two classes, Person and Man, and demonstrates the usage of class methods and inheritance.

Python
from datetime import date

# random Person
class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age

    @staticmethod
    def from_FathersAge(name, fatherAge, fatherPersonAgeDiff):
        return Person(name, date.today().year - fatherAge + fatherPersonAgeDiff)

    @classmethod
    def from_BirthYear(cls, name, birthYear):
        return cls(name, date.today().year - birthYear)

    def display(self):
        print(self.name + "'s age is: " + str(self.age))

class Man(Person):
    sex = 'Female'

man = Man.from_BirthYear('John', 1985)
print(isinstance(man, Man))

man1 = Man.from_FathersAge('John', 1965, 20)
print(isinstance(man1, Man))

Output
True
False

Python @classmethod Decorator

The @classmethod decorator is a built-in function decorator which is an expression that gets evaluated after your function is defined. The result of that evaluation shadows your function definition. A class method receives the class as the implicit first argument, just like an instance method receives the instance.

Syntax of classmethod Decorator

class C(object):  

   @classmethod

      def fun(cls, arg1, arg2, …):

       ….

Where,

  • fun: the function that needs to be converted into a class method
  • returns: a class method for function.

Note:

  • A class method is a method that is bound to the class and not the object of the class.
  • They have the access to the state of the class as it takes a class parameter that points to the class and not the object instance.
  • It can modify a class state that would apply across all the instances of the class. For example, it can modify a class variable that would be applicable to all instances.

Example 

In the below example, we use a staticmethod() and classmethod() to check if a person is an adult or not.

Python
# Python program to demonstrate
# use of a class method and static method.

from datetime import date

class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age

    # a class method to create a
    # Person object by birth year.
    @classmethod
    def fromBirthYear(cls, name, year):
        return cls(name, date.today().year - year)

    # a static method to check if a
    # Person is adult or not.
    @staticmethod
    def isAdult(age):
        return age >= 18

# Creating an instance using the constructor
person1 = Person('Mayank', 21)

# Creating an instance using the class method
person2 = Person.fromBirthYear('Mayank', 1996)

print(f"Person1 Age: {person1.age}")
print(f"Person2 Age: {person2.age}")

# Checking if person1 is an adult
print(f"Is Person1 an adult? {'Yes' if Person.isAdult(person1.age) else 'No'}")

# Checking if person2 is an adult
print(f"Is Person2 an adult? {'Yes' if Person.isAdult(person2.age) else 'No'}")

Output
Person1 Age: 21
Person2 Age: 28
Is Person1 an adult? Yes
Is Person2 an adult? Yes

classmethod() in Python – FAQs

Is __new__ a class method?

Yes, __new__ is a class method, but it is not defined with the @classmethod decorator. It is a special method in Python that is used to create a new instance of a class. __new__ is called before __init__ and is responsible for returning a new instance of the class.

When you call a class to create an instance, __new__ is the method that actually allocates memory for the new object. It is then followed by the __init__ method to initialize the instance.

Example:

class MyClass:
def __new__(cls):
print("Creating a new instance")
return super().__new__(cls) # Create and return a new instance

def __init__(self):
print("Initializing the instance")

obj = MyClass()
# Output:
# Creating a new instance
# Initializing the instance

What is __str__ class method in Python?

__str__ is a special method used to define the string representation of an object. It is not technically a class method but an instance method. When you use print() or str() on an instance of the class, the __str__ method is called to produce a human-readable string representation of the object.

You can override __str__ to provide a meaningful string output for instances of your class.

Example:

class MyClass:
def __str__(self):
return "This is MyClass instance"

obj = MyClass()
print(obj) # Output: This is MyClass instance

What is the difference between a method and a class method?

  • Method:
    • Instance Method: Takes self as the first parameter. It is used to access or modify instance attributes and can call other instance methods.
    • Example:
      class MyClass:
      def instance_method(self):
      return "This is an instance method"
  • Class Method:
    • Class Method: Takes cls as the first parameter. It is used to access or modify class state that applies across all instances.
    • Decorated with: @classmethod
    • Example:
      class MyClass:
      @classmethod
      def class_method(cls):
      return "This is a class method"

What is the @classmethod decorator in Python?

The @classmethod decorator defines a method that is bound to the class and not the instance. It allows you to call the method on the class itself or on instances of the class. The first parameter of a class method is cls, which refers to the class and not the instance.

Example:

class MyClass:
@classmethod
def class_method(cls):
return f"This is a class method of {cls.__name__}"

print(MyClass.class_method()) # Output: This is a class method of MyClass

What is the difference between self and classmethod?

  • self:
    • Refers to the instance of the class.
    • Used in instance methods to access or modify instance attributes and methods.
    • Example:
      class MyClass:
      def instance_method(self):
      return "This method uses self"
  • @classmethod:
    • Refers to the class itself through the cls parameter.
    • Used to access or modify class-level attributes and methods.
    • Defined using the @classmethod decorator.
    • Example:
      class MyClass:
      @classmethod
      def class_method(cls):
      return "This method uses cls"


Previous Article
Next Article

Similar Reads

Important differences between Python 2.x and Python 3.x with examples
In this article, we will see some important differences between Python 2.x and Python 3.x with the help of some examples. Differences between Python 2.x and Python 3.x Here, we will see the differences in the following libraries and modules: Division operatorprint functionUnicodexrangeError Handling_future_ modulePython Division operatorIf we are p
5 min read
Reading Python File-Like Objects from C | Python
Writing C extension code that consumes data from any Python file-like object (e.g., normal files, StringIO objects, etc.). read() method has to be repeatedly invoke to consume data on a file-like object and take steps to properly decode the resulting data. Given below is a C extension function that merely consumes all of the data on a file-like obj
3 min read
Python | Add Logging to a Python Script
In this article, we will learn how to have scripts and simple programs to write diagnostic information to log files. Code #1 : Using the logging module to add logging to a simple program import logging def main(): # Configure the logging system logging.basicConfig(filename ='app.log', level = logging.ERROR) # Variables (to make the calls that follo
2 min read
Python | Add Logging to Python Libraries
In this article, we will learn how to add a logging capability to a library, but don’t want it to interfere with programs that don’t use logging. For libraries that want to perform logging, create a dedicated logger object, and initially configure it as shown in the code below - Code #1 : C/C++ Code # abc.py import logging log = logging.getLogger(_
2 min read
Python | Index of Non-Zero elements in Python list
Sometimes, while working with python list, we can have a problem in which we need to find positions of all the integers other than 0. This can have application in day-day programming or competitive programming. Let's discuss a shorthand by which we can perform this particular task. Method : Using enumerate() + list comprehension This method can be
6 min read
MySQL-Connector-Python module in Python
MySQL is a Relational Database Management System (RDBMS) whereas the structured Query Language (SQL) is the language used for handling the RDBMS using commands i.e Creating, Inserting, Updating and Deleting the data from the databases. SQL commands are case insensitive i.e CREATE and create signify the same command. In this article, we will be disc
2 min read
Python - Read blob object in python using wand library
BLOB stands for Binary Large OBject. A blob is a data type that can store binary data. This is different than most other data types used in databases, such as integers, floating point numbers, characters, and strings, which store letters and numbers. BLOB is a large complex collection of binary data which is stored in Database. Basically BLOB is us
2 min read
twitter-text-python (ttp) module - Python
twitter-text-python is a Tweet parser and formatter for Python. Amongst many things, the tasks that can be performed by this module are : reply : The username of the handle to which the tweet is being replied to. users : All the usernames mentioned in the tweet. tags : All the hashtags mentioned in the tweet. urls : All the URLs mentioned in the tw
3 min read
Reusable piece of python functionality for wrapping arbitrary blocks of code : Python Context Managers
Context Managers are the tools for wrapping around arbitrary (free-form) blocks of code. One of the primary reasons to use a context manager is resource cleanliness. Context Manager ensures that the process performs steadily upon entering and on exit, it releases the resource. Even when the wrapped code raises an exception, the context manager guar
7 min read
Creating and updating PowerPoint Presentations in Python using python - pptx
python-pptx is library used to create/edit a PowerPoint (.pptx) files. This won't work on MS office 2003 and previous versions. We can add shapes, paragraphs, texts and slides and much more thing using this library. Installation: Open the command prompt on your system and write given below command: pip install python-pptx Let's see some of its usag
4 min read
Python Debugger – Python pdb
Debugging in Python is facilitated by pdb module (python debugger) which comes built-in to the Python standard library. It is actually defined as the class Pdb which internally makes use of bdb(basic debugger functions) and cmd (support for line-oriented command interpreters) modules. The major advantage of pdb is it runs purely in the command line
5 min read
Filter Python list by Predicate in Python
In this article, we will discuss how to filter a python list by using predicate. Filter function is used to filter the elements in the given list of elements with the help of a predicate. A predicate is a function that always returns True or False by performing some condition operations in a filter method Syntax: filter(predicate, list) where, list
2 min read
Python: Iterating With Python Lambda
In Python, the lambda function is an anonymous function. This one expression is evaluated and returned. Thus, We can use lambda functions as a function object. In this article, we will learn how to iterate with lambda in python. Syntax: lambda variable : expression Where, variable is used in the expressionexpression can be an mathematical expressio
2 min read
Python Value Error :Math Domain Error in Python
Errors are the problems in a program due to which the program will stop the execution. One of the errors is 'ValueError: math domain error' in Python. In this article, you will learn why this error occurs and how to fix it with examples. What is 'ValueError: math domain error' in Python?In mathematics, we have certain operations that we consider un
4 min read
Creating Your Own Python IDE in Python
In this article, we are able to embark on an adventure to create your personal Python Integrated Development Environment (IDE) the usage of Python itself, with the assistance of the PyQt library. What is Python IDE?Python IDEs provide a characteristic-rich environment for coding, debugging, and going for walks in Python packages. While there are ma
3 min read
GeeksforGeeks Python Foundation Course - Learn Python in Hindi!
Python - it is not just an ordinary programming language but the doorway or basic prerequisite for getting into numerous tech domains including web development, machine learning, data science, and several others. Though there's no doubt that the alternatives of Python in each of these respective areas are available - but the dominance and popularit
5 min read
Python math.sqrt() function | Find Square Root in Python
sqrt() function returns square root of any number. It is an inbuilt function in Python programming language. In this article, we will learn more about the Python Program to Find the Square Root. sqrt() Function We can calculate square root in Python using the sqrt() function from the math module. In this example, we are calculating the square root
3 min read
Python Image Editor Using Python
You can create a simple image editor using Python by using libraries like Pillow(PIL) which will provide a wide range of image-processing capabilities. In this article, we will learn How to create a simple image editor that can perform various operations like opening an image, resizing it, blurring the image, flipping and rotating the image, and so
13 min read
Python | Set 4 (Dictionary, Keywords in Python)
In the previous two articles (Set 2 and Set 3), we discussed the basics of python. In this article, we will learn more about python and feel the power of python. Dictionary in Python In python, the dictionary is similar to hash or maps in other languages. It consists of key-value pairs. The value can be accessed by a unique key in the dictionary. (
5 min read
Learn DSA with Python | Python Data Structures and Algorithms
This tutorial is a beginner-friendly guide for learning data structures and algorithms using Python. In this article, we will discuss the in-built data structures such as lists, tuples, dictionaries, etc, and some user-defined data structures such as linked lists, trees, graphs, etc, and traversal as well as searching and sorting algorithms with th
15+ min read
Why we write #!/usr/bin/env python on the first line of a Python script?
The shebang line or hashbang line is recognized as the line #!/usr/bin/env python. This helps to point out the location of the interpreter intended for executing a script, especially in Unix-like operating systems. For example, Linux and macOS are Unix-like operating systems whose executable files normally start with a shebang followed by a path to
2 min read
Setting up ROS with Python 3 and Python OpenCV
Setting up a Robot Operating System (ROS) with Python 3 and OpenCV can be a powerful combination for robotics development, enabling you to leverage ROS's robotics middleware with the flexibility and ease of Python programming language along with the computer vision capabilities provided by OpenCV. Here's a step-by-step guide to help you set up ROS
3 min read
What is Python Used For? | 7 Practical Python Applications
Python is an interpreted and object-oriented programming language commonly used for web development, data analysis, artificial intelligence, and more. It features a clean, beginner-friendly, and readable syntax. Due to its ecosystem of libraries, frameworks, and large community support, it has become a top preferred choice for developers in the ind
9 min read
How to Install python-dotenv in Python
Python-dotenv is a Python package that is used to manage & store environment variables. It reads key-value pairs from the “.env” file. How to install python-dotenv?To install python-dotenv using PIP, open your command prompt or terminal and type in this command. pip install python-dotenvVerifying the installationTo verify if you have successful
3 min read
Future of Python : Exploring Python 4.0
The future of Python 4.0 is a topic of great anticipation and speculation within the tech community. Guido van Rossum, the creator of Python, offers exclusive insights into what might lie ahead for this popular programming language. With Python 3.9 approaching its release, many are curious about t the potential for Python 4.0. This article explores
8 min read
Top 10 Python Built-In Decorators That Optimize Python Code Significantly
Python is a widely used high-level, general-purpose programming language. The language offers many benefits to developers, making it a popular choice for a wide range of applications including web development, backend development, machine learning applications, and all cutting-edge software technology, and is preferred for both beginners as well as
12 min read
JavaScript vs Python : Can Python Overtop JavaScript by 2020?
This is the Clash of the Titans!! And no...I am not talking about the Hollywood movie (don’t bother watching it...it's horrible!). I am talking about JavaScript and Python , two of the most popular programming languages in existence today. JavaScript is currently the most commonly used programming language (and has been for quite some time!) but no
5 min read
Sort Python Dictionary by Key or Value - Python
There are two elements in a Python dictionary-keys and values. You can sort the dictionary by keys, values, or both. In this article, we will discuss the methods of sorting dictionaries by key or value using Python. Sorting Dictionary By Key Using sort()In this example, we will sort the dictionary by keys and the result type will be a dictionary. [
6 min read
How to write an empty function in Python - pass statement?
In C/C++ and Java, we can write empty function as following // An empty function in C/C++/Java void fun() { } In Python, if we write something like following in Python, it would produce compiler error. # Incorrect empty function in Python def fun(): Output : IndentationError: expected an indented block In Python, to write empty functions, we use pa
1 min read
str() vs repr() in Python
In Python, the str() and repr() functions are used to obtain string representations of objects. While they may seem similar at first glance, there are some differences in how they behave. Both of the functions can be helpful in debugging or printing useful information about the object. Python str() In the given example, we are using the str() funct
3 min read
Article Tags :
Practice Tags :
three90RightbarBannerImg