Skip to content

Python classmethod decorator | @classmethod example code

  • by

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

A simple example code creates a class method using classmethod().

class Student:
    school_name = 'The Xavier Institute'

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

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

# Access Class Method


Python classmethod decorator

Calling Class Method using Object

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

# Access Class Method
s1 = Student()

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 having to initialize your class only once. like opening a file once, and using the feed method to read the file line by line.

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

Note: IDE: PyCharm 2021.3.3 (Community Edition)

Windows 10

Python 3.10.1

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

Leave a Reply

Your email address will not be published. Required fields are marked *