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()
OutputThe 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))
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'}")
OutputPerson1 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?
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?
Similar Reads
Python OOPs Concepts
Object Oriented Programming is a fundamental concept in Python, empowering developers to build modular, maintainable, and scalable applications. By understanding the core OOP principles (classes, objects, inheritance, encapsulation, polymorphism, and abstraction), programmers can leverage the full p
11 min read
Python Classes and Objects
A class in Python is a user-defined template for creating objects. It bundles data and functions together, making it easier to manage and use them. When we create a new class, we define a new type of object. We can then create multiple instances of this object type. Classes are created using class k
6 min read
Python objects
A class is a user-defined blueprint or prototype from which objects are created. Classes provide a means of bundling data and functionality together. Creating a new class creates a new type of object, allowing new instances of that type to be made. Each class instance can have attributes attached to
2 min read
Class and Object
self in Python class
Self represents the instance of the class. By using the "self" we can access the attributes and methods of the class in Python. It binds the attributes with the given arguments. The reason you need to use self. is because Python does not use the @ syntax to refer to instance attributes. Python decid
6 min read
Class and Instance Attributes in Python
Class attributes: Class attributes belong to the class itself they will be shared by all the instances. Such attributes are defined in the class body parts usually at the top, for legibility. [GFGTABS] Python # Write Python code here class sampleclass: count = 0 # class attribute def increase(self):
2 min read
Create a Python Subclass
In Python, a subclass is a class that inherits attributes and methods from another class, known as the superclass or parent class. When you create a subclass, it can reuse and extend the functionality of the superclass. This allows you to create specialized versions of existing classes without havin
3 min read
Inner Class in Python
Python is an Object-Oriented Programming Language, everything in Python is related to objects, methods, and properties. A class is a user-defined blueprint or a prototype, which we can use to create the objects of a class. The class is defined by using the class keyword. Example of class [GFGTABS] P
5 min read
Python MetaClasses
The key concept of python is objects. Almost everything in python is an object, which includes functions and as well as classes. As a result, functions and classes can be passed as arguments, can exist as an instance, and so on. Above all, the concept of objects let the classes in generating other c
9 min read
Creating Instance Objects in Python
In Python, an instance object is an instantiation of a class, and it is a unique occurrence of that class. Creating instance objects is a fundamental concept in object-oriented programming (OOP) and allows developers to work with and manipulate specific instances of a class. This article will explor
3 min read
Dynamic Attributes in Python
Dynamic attributes in Python are terminologies for attributes that are defined at runtime, after creating the objects or instances. In Python we call all functions, methods also as an object. So you can define a dynamic instance attribute for nearly anything in Python. Consider the below example for
2 min read
Constructors in Python
In Python, a constructor is a special method that is called automatically when an object is created from a class. Its main role is to initialize the object by setting up its attributes or state. The method __new__ is the constructor that creates a new instance of the class while __init__ is the init
3 min read
Why Python Uses 'Self' as Default Argument
In Python, when defining methods within a class, the first parameter is always self. The parameter self is a convention not a keyword and it plays a key role in Python’s object-oriented structure. Example: [GFGTABS] Python class Car: def __init__(self, brand, model): self.brand = brand # Set instanc
3 min read
Encapsulation and Access Modifiers
Encapsulation in Python
In Python, encapsulation refers to the bundling of data (attributes) and methods (functions) that operate on the data into a single unit, typically a class. It also restricts direct access to some components, which helps protect the integrity of the data and ensures proper usage. Table of Content En
6 min read
Access Modifiers in Python : Public, Private and Protected
Prerequisites: Underscore (_) in Python, Private Variables in Python Encapsulation is one of the four principles used in Object Oriented Paradigm. It is used to bind and hide data to the class. Data hiding is also referred as Scoping and the accessibility of a method or a field of a class can be cha
9 min read
Access Modifiers in Python : Public, Private and Protected
Prerequisites: Underscore (_) in Python, Private Variables in Python Encapsulation is one of the four principles used in Object Oriented Paradigm. It is used to bind and hide data to the class. Data hiding is also referred as Scoping and the accessibility of a method or a field of a class can be cha
9 min read
Private Variables in Python
Prerequisite: Underscore in PythonIn Python, there is no existence of “Private” instance variables that cannot be accessed except inside an object. However, a convention is being followed by most Python code and coders i.e., a name prefixed with an underscore, For e.g. _geek should be treated as a n
3 min read
Private Methods in Python
Encapsulation is one of the fundamental concepts in object-oriented programming (OOP) in Python. It describes the idea of wrapping data and the methods that work on data within one unit. This puts restrictions on accessing variables and methods directly and can prevent the accidental modification of
6 min read
Protected variable in Python
Prerequisites: Underscore ( _ ) in Python A Variable is an identifier that we assign to a memory location which is used to hold values in a computer program. Variables are named locations of storage in the program. Based on access specification, variables can be public, protected and private in a cl
2 min read
Inheritance
Inheritance in Python
Inheritance is a fundamental concept in object-oriented programming (OOP) that allows a class (called a child or derived class) to inherit attributes and methods from another class (called a parent or base class). This promotes code reuse, modularity, and a hierarchical class structure. In this arti
7 min read
Method Overriding in Python
Method overriding is an ability of any object-oriented programming language that allows a subclass or child class to provide a specific implementation of a method that is already provided by one of its super-classes or parent classes. When a method in a subclass has the same name, the same parameter
7 min read
Operator Overloading in Python
Operator Overloading means giving extended meaning beyond their predefined operational meaning. For example operator + is used to add two integers as well as join two strings and merge two lists. It is achievable because '+' operator is overloaded by int class and str class. You might have noticed t
9 min read
Python super()
In Python, the super() function is used to refer to the parent class or superclass. It allows you to call methods defined in the superclass from the subclass, enabling you to extend and customize the functionality inherited from the parent class. Syntax of super() in PythonSyntax: super() Return : R
8 min read
Multiple Inheritance in Python
Inheritance is the mechanism to achieve the re-usability of code as one class(child class) can derive the properties of another class(parent class). It also provides transitivity ie. if class C inherits from P then all the sub-classes of C would also inherit from P. Multiple Inheritance When a class
5 min read
What Is Hybrid Inheritance In Python?
Inheritance is a fundamental concept in object-oriented programming (OOP) where a class can inherit attributes and methods from another class. Hybrid inheritance is a combination of more than one type of inheritance. In this article, we will learn about hybrid inheritance in Python. Hybrid Inheritan
3 min read
Multilevel Inheritance in Python
Python is one of the most popular and widely used Programming Languages. Python is an Object Oriented Programming language which means it has features like Inheritance, Encapsulation, Polymorphism, and Abstraction. In this article, we are going to learn about Multilevel Inheritance in Python. Pre-Re
3 min read
Multilevel Inheritance in Python
Python is one of the most popular and widely used Programming Languages. Python is an Object Oriented Programming language which means it has features like Inheritance, Encapsulation, Polymorphism, and Abstraction. In this article, we are going to learn about Multilevel Inheritance in Python. Pre-Re
3 min read
Special Methods and Testing