classmethod() in Python


A class method receives the class itself as its first argument. This way we are able to call the method inside a class without first creating an instance from the class. We just use the decorator @classmethod before the declaration of the method contained in the class and then we can directly access the method. Below are the main features of classmethids.

  • A classmethod is bound to a class and does not depend on the instantiation of a class to be used.

  • A classmethod can modify a class which in turn propagates to all instances of the class.

Using the classmethod

In the below example we create a class called WeekDay and create a method in it called daynames. Then we access this method without first instantiating the class which means without creating any object from the class.

Example

class WeekDay:
   day_name = ['Mon','Tue','Wed','Thu','Fri']
# Applying the class method
   @classmethod
   def daynames(n):
      print('The WeekDays are', n.day_name)

WeekDay.daynames()
# OR
WeekDay().daynames()

Output

Running the above code gives us the following result −

The WeekDays are ['Mon', 'Tue', 'Wed', 'Thu', 'Fri']
The WeekDays are ['Mon', 'Tue', 'Wed', 'Thu', 'Fri']

Without using the classmethod

To achieve the same result without a classmethod we can declare the method without a class. This shows the reason for which we need the class method.

Example

def daynames():
   day_name = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri']
   print('The WeekDays are', day_name)

daynames()

Output

Running the above code gives us the following result −

The WeekDays are ['Mon', 'Tue', 'Wed', 'Thu', 'Fri']

Updated on: 17-Oct-2019

343 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements