Python Class Methods

🐍 Python Class Methods — Complete Guide

In Python, class methods are methods that operate on the class itself, not on instances (objects).
They are defined using the @classmethod decorator.


🔹 1️⃣ Key Points About Class Methods

  • Decorated with @classmethod.

  • First parameter is cls, which refers to the class, not the instance.

  • Can access class variables but cannot access instance variables directly.

  • Can be called on the class or on an instance.


🔹 2️⃣ Basic Syntax

class MyClass:
class_var = 0
@classmethod
def show_class_var(cls):
print(“Class variable:”, cls.class_var)

Call the method:

MyClass.show_class_var() # Class variable: 0

Or via object:

obj = MyClass()
obj.show_class_var() # Class variable: 0

🔹 3️⃣ Example: Incrementing a Class Variable

class Employee:
employee_count = 0 # class variable
def __init__(self, name):
self.name = name
Employee.employee_count += 1

@classmethod
def total_employees(cls):
print(f”Total Employees: {cls.employee_count}“)

e1 = Employee(“Vipul”)
e2 = Employee(“Riya”)

Employee.total_employees() # Total Employees: 2


🔹 4️⃣ Factory Method Using Class Method

Class methods can also be used as factory methods to create objects with alternative constructors.

class Person:
def __init__(self, name, age):
self.name = name
self.age = age
@classmethod
def from_string(cls, data_str):
name, age = data_str.split(“-“)
return cls(name, int(age))

p1 = Person.from_string(“Vipul-25”)
print(p1.name) # Vipul
print(p1.age) # 25


🔹 5️⃣ Difference Between Instance Method and Class Method

Feature Instance Method Class Method
Decorator None @classmethod
First Parameter self (object) cls (class)
Access Instance variables Class variables
Call On object only On object or class

🔹 6️⃣ Class Method vs Static Method (Quick Comparison)

Feature Class Method Static Method
Decorator @classmethod @staticmethod
First Param cls None
Access Class variables Cannot access class or instance vars
Use Factory methods, class-level logic Utility functions

🔹 7️⃣ Real-World Example: Bank Account

class Bank:
bank_name = "ABC Bank"
accounts = 0
def __init__(self, owner, balance):
self.owner = owner
self.balance = balance
Bank.accounts += 1

@classmethod
def bank_info(cls):
print(f”Bank: {cls.bank_name}, Total Accounts: {cls.accounts}“)

b1 = Bank(“Vipul”, 5000)
b2 = Bank(“Riya”, 10000)

Bank.bank_info() # Bank: ABC Bank, Total Accounts: 2


✅ Summary

  • Instance Method → works on object (self)

  • Class Method → works on class (cls)

  • Static Method → utility method, independent of object/class

CodeCapsule

Sanjit Sinha — Web Developer | PHP • Laravel • CodeIgniter • MySQL • Bootstrap Founder, CodeCapsule — Student projects & practical coding guides. Email: info@codecapsule.in • Website: CodeCapsule.in

You may also like...

Leave a Reply

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