Last Updated : 11 Jul, 2025
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 SyntaxPython classmethod() Functionclass MyClass:
@classmethod
def class_method(cls, *args, **kwargs):
# Method implementation
pass
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 MethodThe basic difference between the class method vs Static method in Python and when to use the class method and static method in Python.
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."
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: DSACreate class method using classmethod()
Number of instances: 2
Welcome to Geeks for Geeks!
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()
The name is : GeeksforgeeksFactory 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 16How 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.
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))
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 Decoratorclass 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:
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'}")
Person1 Age: 21 Person2 Age: 28 Is Person1 an adult? Yes Is Person2 an adult? Yes
self
as the first parameter. It is used to access or modify instance attributes and can call other instance methods.class MyClass:
def instance_method(self):
return "This is an instance method"
cls
as the first parameter. It is used to access or modify class state that applies across all instances.@classmethod
class MyClass:
@classmethod
def class_method(cls):
return "This is a class method"
@classmethod
decorator in Python?
What is the difference betweenThe
@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 iscls
, 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
self
and classmethod
?
self
:
class MyClass:
def instance_method(self):
return "This method uses self"
@classmethod
:
cls
parameter.@classmethod
decorator.class MyClass:
@classmethod
def class_method(cls):
return "This method uses cls"
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4