🏛️ Python OOP — Class Methods

Introduction 🌟

A Class Method is a method that works on the **class itself**, not on objects. Instead of taking self, a class method takes cls as its first parameter, where cls refers to the **class**, not the instance.

Note

💡 Use class methods when you want to access or modify **class attributes** or create alternative constructors.

1. Defining a Class Method 🧱

basic_classmethod.py

class Student:
    school = "Govt School"

    @classmethod
    def get_school(cls):         # clsclass reference
        return cls.school

print(Student.get_school())

✔ Class methods are called using the **class name**
@classmethod decorator is required

2. Accessing and Modifying Class Attributes 🛠️

modify_class_attr.py

class Student:
    school = "Govt School"

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

Student.change_school("Public School")
print(Student.school)

Note

✔ Perfect use-case: updating shared (global) values for all objects.

3. Class Method vs Instance Method ⚔️

Instance MethodClass Method
First parameter = selfFirst parameter = cls
Works on instance-level dataWorks on class-level data
Called using objectCalled using class or object

4. Calling Class Methods Using Objects 👤

call_with_object.py

class Demo:
    msg = "Hello!"

    @classmethod
    def show(cls):
        print(cls.msg)

d = Demo()
d.show()   # allowed

✔ Even though an object calls it, the method works on the class.

5. Class Methods as Alternative Constructors 🏗️

Class methods are commonly used to create alternative constructors— special ways to create objects.

alt_constructor.py

class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age

    @classmethod
    def from_string(cls, info):
        name, age = info.split("-")
        return cls(name, int(age))

p = Person.from_string("Sathish-23")
print(p.name, p.age)

Note

✔ Useful when parsing data from files, APIs, databases, etc.

6. Real-World Example: Employee ID Generator 🧮

employee_id.py

class Employee:
    company = "Google"
    emp_count = 0

    def __init__(self, name):
        self.name = name
        Employee.emp_count += 1
        self.id = Employee.emp_count

    @classmethod
    def total_employees(cls):
        return cls.emp_count

e1 = Employee("Sathish")
e2 = Employee("Kumar")

print(Employee.total_employees())

✔ Class method returns info about all objects collectively.

7. Real-World Example: App Configuration 🔧

app_config.py

class Config:
    version = "1.0"
    theme = "light"

    @classmethod
    def update_theme(cls, new_theme):
        cls.theme = new_theme

Config.update_theme("dark")
print(Config.theme)

8. Using Class Method with Inheritance 👨‍👩‍👦

inheritance_classmethod.py

class Animal:
    species = "Unknown"

    @classmethod
    def info(cls):
        print("Species:", cls.species)

class Dog(Animal):
    species = "Dog"

Dog.info()  # Species: Dog

✔ Class methods automatically work with subclasses via cls.

9. Best Practices 💡

  • ✔ Use class methods to modify class attributes
  • ✔ Use for alternative constructors
  • ✔ Access class attributes using cls
  • ✔ Prefer instance methods when dealing with object-specific data
  • ✔ Use clear naming like from_…() for alternative constructors

Conclusion 🎉

>>“Class Methods operate at the class level — perfect for shared data and alternative ways of creating objects.” ✨

You now fully understand Class Methods in Python! Want the next topic? Try Static Methods, Constructors, Inheritance, or Encapsulation. Just tell me! 😊