Class Methods, Static Methods, and Instance Methods in Python

Python provides three types of methods in a class: Instance Methods, Class Methods, and Static Methods. Each serves a different purpose and is used based on the requirement. In this article, we’ll explore these methods with examples to understand their differences and use cases.

class method static method instance method

Instance Methods

Instance methods are the most commonly used methods in a class. They have access to both instance variables (attributes) and class variables. They require an instance of the class to be called.

Characteristics:

  • Defined using def with self as the first parameter.
  • Can modify the object’s state (instance attributes).
  • Can access and modify class-level data.

Example:

class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age
    
    def greet(self):
        return f"Hello, my name is {self.name} and I am {self.age} years old."

# Creating an instance
person = Person("Alice", 25)
print(person.greet())  # Output: Hello, my name is Alice and I am 25 years old.
Python

When to Use:

  • When you need to work with instance attributes.
  • When the method behavior depends on the individual object.

Class Methods

Class methods are used when we need to modify or access class-level attributes rather than instance attributes. They are bound to the class and receive cls (class reference) as the first parameter instead of self.

Characteristics:

  • Defined using @classmethod decorator
  • Takes cls as the first parameter
  • Can access and modify class attributes but cannot modify instance attributes
  • shared across all instances

Example:

class Car:
    wheels = 4  # Class attribute
    
    def __init__(self, brand):
        self.brand = brand
    
    @classmethod
    def set_wheels(cls, count):
        cls.wheels = count  # Modifies class attribute
    
    @classmethod
    def get_wheels(cls):
        return f"All cars have {cls.wheels} wheels."

# Modifying class attribute using class method
Car.set_wheels(6)
print(Car.get_wheels())  # Output: All cars have 6 wheels.
Python

When to Use:

  • When a method needs to operate on class variables rather than instance variables.
  • When alternative constructors are needed.

Alternative constructor:

A class method can be used as an alternative constructor to process the data and create an instance.

class Employee:
    def __init__(self, name, age):
        self.name = name
        self.age = age
    
    @classmethod
    def alternative(cls, name, age):
        return cls(name, age)


emp_cons = Employee("Sam",45)
emp_alter = Employee.alternative("John",30)

print(type(emp_cons)) #<class '__main__.Employee'>
print(type(emp_alter)) #<class '__main__.Employee'>
Python

Static Methods

Static methods are independent of both class and instance attributes. They are used when we don’t need to modify class or instance attributes but still want to keep related functionality inside the class.

Characteristics:

  • Defined using @staticmethod decorator.
  • Do not take self or cls as the first parameter.
  • Can be called on an instance or class.

Example:

class MathOperations:
    @staticmethod
    def add(x, y):
        return x + y
    
    @staticmethod
    def multiply(x, y):
        return x * y

# Calling static methods
print(MathOperations.add(5, 3))      # Output: 8
print(MathOperations.multiply(4, 6)) # Output: 24
Python

When to Use:

  • When a method does not depend on instance or class attributes.
  • For utility functions related to the class but do not require access to class/instance data.

Key Differences

FeatureInstance MethodClass MethodStatic Method
Bound toInstanceClassNeither
First Parameterself (instance)cls (class)No self or cls
Can Modify Instance Attributes?Yes No No
Can Modify Class Attributes?YesYesNo
Called UsingInstanceInstance or ClassInstance or Class

Real life Example

Instance Method – Working with Object Attributes

Example: Bank Account System

Imagine a Bank Account where each customer has their own balance and can deposit or withdraw money.

class BankAccount:
    def __init__(self, account_holder, balance=0):
        self.account_holder = account_holder
        self.balance = balance  # Instance attribute

    def deposit(self, amount):
        self.balance += amount
        return f"Deposited {amount}. New Balance: {self.balance}"

    def withdraw(self, amount):
        if amount > self.balance:
            return "Insufficient funds!"
        self.balance -= amount
        return f"Withdrawn {amount}. Remaining Balance: {self.balance}"

# Real-Life Usage
account1 = BankAccount("Alice", 1000)
print(account1.deposit(500))    # Deposited 500. New Balance: 1500
print(account1.withdraw(2000))  # Insufficient funds!
print(account1.withdraw(300))   # Withdrawn 300. Remaining Balance: 1200
Python

Why use an instance method?

  • Each account has its own balance.
  • The deposit and withdraw methods modify the account’s balance, which is unique for every customer.

Class Method – Managing Shared Data

Example: Counting Total Employees in a Company

Imagine a company where we need to track the total number of employees.

class Employee:
    total_employees = 0  # Class attribute (shared by all instances)

    def __init__(self, name):
        self.name = name
        Employee.total_employees += 1  # Updating shared data

    @classmethod
    def get_total_employees(cls):
        return f"Total Employees: {cls.total_employees}"

# Real-Life Usage
emp1 = Employee("John")
emp2 = Employee("Emma")
emp3 = Employee("Liam")

print(Employee.get_total_employees())  # Total Employees: 3
Python

Why use a class method?

  • total_employees is shared across all instances.
  • get_total_employees() provides a way to access and modify class-level data.

Static Method – Utility Functions Inside a Class

Example: Validating Emails for User Registration

Imagine an application where we need to validate user emails before creating an account.

import re

class User:
    def __init__(self, username, email):
        if not self.validate_email(email):
            raise ValueError("Invalid Email Format!")
        self.username = username
        self.email = email

    @staticmethod
    def validate_email(email):
        return re.match(r"[^@]+@[^@]+\.[^@]+", email)

# Real-Life Usage
try:
    user1 = User("alice", "alice@example.com")  # Valid email
    print("User registered successfully!")
except ValueError as e:
    print(e)

try:
    user2 = User("bob", "bob@invalid-email")  # Invalid email
except ValueError as e:
    print(e)  # Output: Invalid Email Format!
Python

Why use a static method?

  • It doesn’t need to modify or access any attributes (instance or class).
  • It’s a self-contained utility function inside the class.
  • Keeps email validation logic inside the User class, maintaining code organization.

Parameter cls, self

cls in class Method

  • cls is a convention used to represent the class itself in class methods.
  • Just like self refers to the instance of a class, cls refers to the class when working with class methods.
  • It allows accessing and modifying class-level attributes.
  • This allows you to modify instance creation, such as implementing a singleton pattern or controlling subclass instantiation.

self in Instance Method

  • Instance methods operate on a specific instance of a class.
  • The first parameter, self, represents the instance itself, giving access to instance attributes and methods.
  • Without self, Python wouldn’t know which instance’s attributes or methods to modify.

No self or cls in Static Methods

  • Static methods do not operate on an instance or class; they are just functions inside a class.
  • They don’t have access to instance (self) or class (cls) attributes unless explicitly passed.
  • Defined using @staticmethod, they are useful for utility functions that logically belong to the class but don’t need access to the class or instance state.

Why cls? , why not use self in class method?

Because the instance doesn’t exist yet, but the class does.

Conclusion

Understanding these three types of methods in Python helps in writing cleaner and more efficient code. Instance methods are used for working with object attributes, class methods work with class attributes, and static methods provide utility functionality that doesn’t rely on instance or class attributes.

  • Use instance methods when working with object-specific data.
  • Use class methods when working with shared data across all instances.
  • Use static methods for utility functions that don’t depend on instance or class attributes.

Resource

1 thought on “Class Methods, Static Methods, and Instance Methods in Python”

Leave a Comment