Python classmethod decorator | @classmethod example code

Using classmethod decorator you can define a class method in Python. You can call this method using ClassName.MethodName().

The first parameter must be cls, which can be used to access class attributes and only access the class attributes but not the instance attributes.

Python classmethod decorator example

Simple example code creates class method using classmethod().

class Student:
    school_name = 'The Xavier Institute'

    def __init__(self):
        self.age = 20  # instance attribute

    @classmethod
    def display(cls):
        print('School:', cls.school_name)

# Access Class Method
Student.display()

Output:

Python classmethod decorator

Calling Class Method using Object

However, the same method can be called using an object also.

# Access Class Method
s1 = Student()
s1.display()

Note: The class method can only access class attributes, but not the instance attributes.

When to use @classmethod decorator Python?

Answer: class methods for any methods that are not bound to a specific instance but the class.

Python classmethod is useful when making that class as a factory or have to initialize your class only once. like open file once, and using the feed method to read the file line by line.

Do comment if you have any doubts and suggestions on this Python decorator topic.

Note: IDE: PyCharm 2021.1.3 (Community Edition)

Windows 10

Python 3.7

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.


Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.