Python class method | Basics

A method that is bound to the class and not the object of the class is called a class method in Python. Class methods are not on a specific object instance. It belongs to a class level, and all class instances (Object) share a class method.

Call class method

ClassName.method_name()

the @classmethod decorator is used to declaring a method in the class as a class method. The class method can also be called using an object of the class.

Python class method example code

Simple example code declares a class method and accesses it. Use this method for any methods that are not bound to a specific instance but the class.

class Student:
    school_name = 'King kong'  # class attribute

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

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


Student.tostring()

Output:

Python class method

Python class method Implementation demonstration

Python class method Implementation demonstration

Another Example

You can also classmethod() function to define a class method in Python. It is used to convert a normal method into a class method.

classmethod(function)

It returns a class method for a given function.

class School:
    # class variable
    name = 'ABC School'

    def school_name(cls):
        print('School Name is :', cls.name)


# create class method
School.school_name = classmethod(School.school_name)

# call class method
School.school_name()

Output: School Name is : ABC School

Do comment if you have any doubts and suggestions on this Python Python basic method 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.