- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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']