In Object-oriented programming, we use instance methods and class methods. Inside a Class, we can define the following three types of methods.
- Instance method: Used to access or modify the object state. If we use instance variables inside a method, such methods are called instance methods. It must have a
self
parameter to refer to the current object. - Class method: Used to access or modify the class state. In method implementation, if we use only class variables, then such type of methods we should declare as a class method. The class method has a
cls
parameter which refers to the class. - Static method: It is a general utility method that performs a task in isolation. Inside this method, we don’t use instance or class variable because this static method doesn’t take any parameters like
self
andcls
.
Also, read Python Class method vs Static method vs Instance method.
After reading this article, you’ll learn:
- How to create and use the class methods in Python
- Create class method using the
@classmethod
decorator andclassmethod()
function - how to dynamically add or delete class methods
Table of contents
What is Class Method in Python
Class methods are methods that are called on the class itself, not on a specific object instance. Therefore, it belongs to a class level, and all class instances share a class method.
- A class method is bound to the class and not the object of the class. It can access only class variables.
- It can modify the class state by changing the value of a class variable that would apply across all the class objects.
In method implementation, if we use only class variables, we should declare such methods as class methods. The class method has a cls
as the first parameter, which refers to the class.
Class methods are used when we are dealing with factory methods. Factory methods are those methods that return a class object for different use cases. Thus, factory methods create concrete implementations of a common interface.
The class method can be called using ClassName.method_name()
as well as by using an object of the class.
Define Class Method
Any method we create in a class will automatically be created as an instance method. We must explicitly tell Python that it is a class method using the @classmethod
decorator or classmethod()
function.
Class methods are defined inside a class, and it is pretty similar to defining a regular function.
Like, inside an instance method, we use the self
keyword to access or modify the instance variables. Same inside the class method, we use the cls
keyword as a first parameter to access class variables. Therefore the class method gives us control of changing the class state.
- You may use a variable named differently for
cls
, but it is discouraged since self is the recommended convention in Python. - The class method can only access the class attributes, not the instance attributes
Example 1: Create Class Method Using @classmethod Decorator
To make a method as class method, add @classmethod
decorator before the method definition, and add cls
as the first parameter to the method.
The @classmethod
decorator is a built-in function decorator. In Python, we use the @classmethod
decorator to declare a method as a class method. The @classmethod
decorator is an expression that gets evaluated after our function is defined.
Let’s see how to create a factory method using the class method. In this example, we will create a Student class object using the class method.
Output
Jessa's age is: 20
John's age is: 26
- In the above example, we created two objects, one using the constructor and the second using the
calculate_age()
method. - The constructor takes two arguments name and age. On the other hand, class method takes
cls
,name
, andbirth_year
and returns a class instance which nothing but a new object. - The
@classmethod
decorator is used for convertingcalculate_age()
method to a class method. - The
calculate_age()
method takes Student class (cls
) as a first parameter and returns constructor by callingStudent(name, date.today().year - birthYear)
, which is equivalent toStudent(name, age)
.
Example 2: Create Class Method Using classmethod() function
Apart from a decorator, the built-in function classmethod()
is used to convert a normal method into a class method. The classmethod()
is an inbuilt function in Python, which returns a class method for a given function.
Syntax:
classmethod(function)
Code language: Python (python)
function
: It is the name of the method you want to convert as a class method.- It returns the converted class method.
Note: The method you want to convert as a class method must accept class (cls
) as the first argument, just like an instance method receives the instance (self
).
As we know, the class method is bound to class rather than an object. So we can call the class method both by calling class and object.
A classmethod()
function is the older way to create the class method in Python. In a newer version of Python, we should use the @classmethod
decorator to create a class method.
Example: Create class method using classmethod()
function
Output
School Name is : ABC School
Example 3: Access Class Variables in Class Methods
Using the class method, we can only access or modify the class variables. Let’s see how to access and modify the class variables in the class method.
Class variables are shared by all instances of a class. Using the class method we can modify the class state by changing the value of a class variable that would apply across all the class objects.
Output:
Jessa 20 School: ABC School
Jessa 20 School: XYZ School
Class Method in Inheritance
In inheritance, the class method of a parent class is available to a child class.
Let’s create a Vehicle class that contains a factory class method from_price() that will return a Vehicle instance from a price. When we call the same method using the child’s class name, it will return the child’s class object.
Whenever we derive a class from a parent class that has a class method then it creates the correct instance of the derived class. The following example shows how the class method works in inheritance.
Example
Output
BMW X5 65000 BMW X5 4875000 class '__main__.Car'
Dynamically Add Class Method to a Class
Typically, we add class methods to a class body when defining a class. However, Python is a dynamic language that allows us to add or delete methods at runtime. Therefore, it is helpful when you wanted to extend the class functionality without changing its basic structure because many systems use the same structure.
We need to use the classmethod()
function to add a new class method to a class.
Example:
Let’s see how to add a new class method in the Student class at runtime.
Output
Jessa 14 Below exercises for ABC School
Dynamically Delete Class Methods
We can dynamically delete the class methods from the class. In Python, there are two ways to do it:
- By using the
del
operator - By using
delattr()
method
By using the del
operator
The del
operator removes the instance method added by class. Use the del class_name.class_method
syntax to delete the class method.
Example:
In this example, we will delete the class method named change_school()
from a Student class. If you try to access it after removing it, you’ll get an Attribute Error.
Output
XYZ School AttributeError: type object 'Student' has no attribute 'change_school'
By using delatt()
method
The delattr()
method is used to delete the named attribute and method from the class. The argument to delattr
is an object and string. The string must be the name of an attribute or method name.
Example
Output
XYZ School AttributeError: type object 'Student' has no attribute 'change_school'
Chris W says
Very good tutorial.. But ‘name’ has no place in the definition of calculate_age. It’s a class variable and should be included as such.
Tushar Kathane says
very nice article
Arun says
Great work. Im loving learnging this.
I have one question though.
When you return from class_method return cls(name, date.today().year – birth_year). how is this value being assigned to age?
@classmethod
def calculate_age(cls, name, birth_year):
# calculate age an set it as a age
# return new object
return cls(name, date.today().year – birth_year)
joy = Student.calculate_age(‘Joy’,1995)
print(joy.name)
print(joy.age)
Jessa
20
Ju Arv says
Thanks! So informative representation. I love it
yassine afaila says
thank you so much
Alireza says
A very helpful and well-explained article; well done.
Just in the first example’s code box, you are instantiating the ‘joy’ instance with the name attribute ‘Joy’, but in the result of
joy.show()
, you returned ‘John’ as the name attribute of joy’s instance.Were says
Had given hope of learning python by myself,,,,
But now I am back an doing well
Anurag says
PYNative tutorials are pretty easy to follow with step-by-step examples. For the first time, I feel like I am getting a proper sense of python and after following your tutorial, I am now starting to enjoy Python.
Thank you, Vishal.
Request: please keep posting new things in python especially Numpy if you don’t mind 🙂
Rahul jaiswar says
Thank you sir,
your articles are very useful
Raju Srinivas says
well done Vishal, your articles are very helpful, seen many of them but PYNative is the best.