Header Ads Widget

⚡ Premium Tools Hub • EXE Apps + Full Python Source Code
Lite • Pro • Bundle Packs • Instant Download

Python - Class Methods (Complete Guide for Beginners)

 In Python Object-Oriented Programming (OOP), class methods are methods that belong to the class rather than individual objects. They can access and modify class attributes and are often used to create utility functions that operate on class-level data.

Python provides the @classmethod decorator to define class methods.

In this tutorial, you will learn how class methods work, how to create them, and when to use them.


What is a Class Method?

A class method is a method that is bound to the class and not the object.

Unlike instance methods, which use self, class methods use cls as their first parameter.

Syntax

class ClassName:

    @classmethod
    def method_name(cls):
        pass

Why Use Class Methods?

Class methods are useful when you need to:

  • Access class attributes
  • Modify class-level data
  • Create alternative constructors
  • Perform operations related to the class

Creating Your First Class Method

Example

class Student:

    school = "ABC School"

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

Student.show_school()

Output

ABC School

Understanding cls Parameter

The cls parameter refers to the class itself.

Example

class Employee:

    company = "Tech Corp"

    @classmethod
    def display_company(cls):
        print(cls.company)

Employee.display_company()

Output

Tech Corp

Accessing Class Attributes

Class methods can directly access class variables.

Example

class Car:

    manufacturer = "Toyota"

    @classmethod
    def show_manufacturer(cls):
        print(cls.manufacturer)

Car.show_manufacturer()

Modifying Class Attributes

Class methods can change shared class data.

Example

class Student:

    school = "ABC School"

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

Student.change_school("XYZ School")

print(Student.school)

Output

XYZ School

Calling Class Methods Through Objects

Class methods can also be called using objects.

Example

class Student:

    school = "ABC School"

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

s1 = Student()

s1.show_school()

Class Method vs Instance Method

Instance Method

class Student:

    def show(self):
        print("Instance Method")

Uses:

s1.show()

Class Method

class Student:

    @classmethod
    def show(cls):
        print("Class Method")

Uses:

Student.show()

Difference Between Instance and Class Methods

FeatureInstance MethodClass Method
First Parameterselfcls
Access Object DataYesNo
Access Class DataYesYes
Called ByObjectClass or Object
Decorator RequiredNo@classmethod

Alternative Constructor Using Class Method

One common use of class methods is creating alternative constructors.

Example

class Student:

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

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

student = Student.from_string("John-20")

print(student.name)
print(student.age)

Output

John
20

Real-World Example: School Management System

class Student:

    school_name = "Green Valley School"

    @classmethod
    def display_school(cls):
        print("School:", cls.school_name)

Student.display_school()

Real-World Example: Company System

class Employee:

    company = "Global Tech"

    @classmethod
    def update_company(cls, new_name):
        cls.company = new_name

Employee.update_company("Future Tech")

print(Employee.company)

Combining Instance and Class Methods

Example

class Product:

    tax_rate = 10

    def __init__(self, price):
        self.price = price

    @classmethod
    def show_tax(cls):
        print("Tax Rate:", cls.tax_rate)

p1 = Product(500)

p1.show_tax()

Common Mistakes

Mistake 1: Forgetting @classmethod

❌ Wrong

class Test:

    def show(cls):
        print("Hello")

✔ Correct

class Test:

    @classmethod
    def show(cls):
        print("Hello")

Mistake 2: Using self Instead of cls

❌ Wrong

@classmethod
def show(self):
    pass

✔ Correct

@classmethod
def show(cls):
    pass

Mistake 3: Accessing Instance Variables

Class methods cannot directly access object-specific attributes.

❌ Wrong

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

✔ Use class attributes instead.


Best Practices

  • Use class methods for shared data.
  • Use instance methods for object-specific data.
  • Use meaningful class method names.
  • Keep class methods focused on class-level operations.

Class Methods Summary

Method TypePurpose
Instance MethodWorks with object data
Class MethodWorks with class data
Static MethodUtility function

Conclusion

Class methods are a powerful feature of Python OOP that allow you to work with class-level data efficiently.

You learned:

  • What class methods are
  • How to create them using @classmethod
  • The purpose of the cls parameter
  • How to access and modify class attributes
  • Alternative constructors
  • Real-world examples

Understanding class methods will help you write cleaner, more maintainable, and more professional object-oriented Python code.


Practice Exercises

Exercise 1

Create a class named Book with a class attribute called library_name. Create a class method to display the library name.


Exercise 2

Create a class named Employee with a class attribute company. Create a class method that updates the company name.




Post a Comment

0 Comments