Notes

Class Method in Python [ English ]

< Prev Next >

1. Introduction

A class method in Python is a method that is bound to the class rather than the object (instance). It can access and modify class-level data (class variables) but not instance-specific data directly.

Class methods are defined using the @classmethod decorator.

2. Definition

A class method is a method that:

3. Syntax

class ClassName:
    @classmethod
    def method_name(cls):
        # code

4. Basic Example

class Student:
    school = "ABC School"

    @classmethod
    def show_school(cls):
        print("School:", cls.school)

Student.show_school()

Output

School: ABC School

5. Using Class Method with Objects

class Student:
    school = "ABC School"

    @classmethod
    def show_school(cls):
        print(cls.school)

s1 = Student()
s1.show_school()

6. Key Difference: self vs cls

Feature Instance Method Class Method
First parameter self cls
Access Instance variables Class variables
Called by Object Class or Object

7. Modifying Class Variables

class Student:
    school = "ABC School"

    @classmethod
    def change_school(cls, new_name):
        cls.school = new_name

Student.change_school("XYZ School")

print(Student.school)

Output

XYZ School

8. Class Method as Alternative Constructor

Class methods are often used to create alternative constructors.

class Student:
    def __init__(self, name):
        self.name = name

    @classmethod
    def from_string(cls, data):
        name = data.split("-")[0]
        return cls(name)

s1 = Student.from_string("Rahul-20")

print(s1.name)

9. When to Use Class Methods

Use class methods when:

10. Important Points

11. Summary

< Prev Next >