Artificial Intelligence & Data Science is coming soon

We're still writing and reviewing the notes for every subject, and we'll open it when every subject is ready. Meanwhile you can practise aptitude, ask Aria about any subject, or see the branches that are ready.

Object-oriented programming concepts

Object-oriented programming concepts: real-world modeling with classes/objects, encapsulation, abstraction, relationships (association/aggregation/composition), interfaces/duck typing, methods (instance/class/static), attributes, constructors, message passing, cohesion/coupling, and basic design not

Drafted with Aria, reviewed by the AiCanCode.org team · Updated . How we write and check our notes. Spotted an error? Use Give Feedback at the bottom of the page.

Why it matters

Object-oriented programming (OOP) helps you model real-world systems in software by grouping data with the operations on that data. Engineers use OOP to build maintainable, reusable, and testable code for products like embedded controllers, data processing pipelines, GUIs, and simulations.

Key ideas

  • Definition: A class is a user-defined blueprint that specifies the attributes (data) and methods (functions) common to all its objects. Assumption: instances are created from a class using a constructor. (Detailed coding is in the topic “Classes and objects in Python”.)
  • Definition: Attribute (also called field; note: in Python a 'property' is a descriptor that controls access to an attribute) is a named value stored inside an object or class that represents its state.
  • Definition: Method is a function bound to a class or an object that operates on the object’s data. In Python, methods are regular functions defined inside a class and called with an object.
  • Definition: Constructor is a special method invoked when an object is created to initialize its attributes. In Python, initialization is done in init; actual object creation happens in new.
  • Definition: Encapsulation is the bundling of data and the methods that operate on that data into a single unit, and the controlled exposure of that data through a public interface. Exact statement: In OOP, encapsulation hides internal representation and enforces access via methods/properties to maintain invariants.
    • Assumption: clients use the public interface; the class maintains its own consistency.
    • In Python, name-mangling (prefix __) and properties help enforce encapsulation by convention.
  • Definition: Abstraction is the process of exposing only the necessary features of an object while hiding unnecessary implementation details. Exact statement: An abstraction defines what an object does, not how it does it.
    • Assumption: users depend on documented behavior (specification) rather than internal code.
  • Definition: Association is a relationship where one object knows about or uses another. It models “uses-a” or “knows-a.”
  • Definition: Aggregation is a special association representing a whole–part relationship where the part can exist independently of the whole (weak ownership). Example: Team and Player.
  • Definition: Composition is a strong whole–part relationship where the part’s lifetime is controlled by the whole (strong ownership). Example: Car and Engine created inside Car.
    • Exact relation statement: In composition the whole owns/manages its parts and the parts' lifetime is bound to the whole; if the whole is destroyed, parts are typically destroyed.
  • Definition: Inheritance is a mechanism for creating a new class (subclass) from an existing class (superclass) to reuse and extend behavior. (Programming details are in “Inheritance and polymorphism in Python”.)
  • Definition: Polymorphism is the ability of different object types to be used interchangeably through a common interface. Exact statement: A single operation name can have different implementations depending on the object’s actual type. In Python, this is often implemented as duck typing: “if it quacks like a duck.”
  • Definition: Interface (informal in Python) is the set of public methods and properties that an object presents to its users. In Python, interfaces are often defined by documentation and checked via duck typing; Abstract Base Classes (ABCs) can formalize them.
  • Definition: Message passing is the act of one object invoking a method on another object, optionally with arguments, to request a service.
  • Definition: Cohesion is the degree to which the responsibilities of a single module/class are related. Exact statement: High cohesion means a class focuses on one well-defined task.
  • Definition: Coupling is the degree of interdependence between modules/classes. Exact statement: Low coupling means changes in one class have minimal impact on others.
  • Principle: Single Responsibility Principle (SRP): A class should have only one reason to change. Assumption: responsibilities are identified from requirements.
  • Principle: Open–Closed Principle (OCP): Software entities should be open for extension, but closed for modification. Assumption: new behavior is added without altering stable code, often via polymorphism or composition.
  • Principle: Liskov Substitution Principle (LSP): Objects of a superclass shall be replaceable with objects of a subclass without breaking correctness. Assumption: subclass preserves the behavioral contract.
  • Principle: Dependency Inversion Principle (DIP): High-level modules should not depend on low-level modules; both should depend on abstractions. Assumption: abstractions are stable and shared.
  • Principle: Interface Segregation Principle (ISP): Clients should not be forced to depend on methods they do not use. Assumption: prefer small, focused interfaces (e.g., narrow ABCs in Python).
  • Python-specific ideas, stated simply:
    • self: the first parameter of an instance method that refers to the current object.
    • Property: a Python feature (property) that exposes a method as an attribute for controlled access (get/set/delete), supporting encapsulation without Java/C++-style access modifiers.
    • Class method: a method decorated with @classmethod that receives the class object as first parameter (cls) and often acts as an alternate constructor or class-level operation.
    • Static method: a method decorated with @staticmethod that has no automatic first parameter; it behaves like a plain function namespaced in the class.
    • Dunder methods: special double-underscore methods that define object protocol behavior (e.g., str, repr, eq, len).
    • Class vs instance attributes: attributes defined on the class are shared by instances (unless shadowed by an instance attribute of the same name); instance attributes are per-object and are typically set in init.

Diagram to draw and label (for exam answers):

  • UML-style class box: a rectangle split into three compartments. Top: class name (e.g., "BankAccount"). Middle: attributes (e.g., "- _balance: float"). Bottom: methods (e.g., "+ deposit(amount: float): None"). Use “+” for public, “-” for private (by convention in Python). Draw a solid line with a diamond at the whole end for aggregation/composition: hollow diamond for aggregation (Team ◇— Player), filled diamond for composition (Car ◆— Engine). Draw an open triangle arrow from subclass to superclass for inheritance.

Derivation-like reasoning often asked conceptually (stepwise comparison):

  1. Start from a problem statement (e.g., “Model a library system”).
  2. Identify nouns as candidate classes (Book, Member, Loan) — abstraction.
  3. Assign attributes (title, author, due_date) — encapsulation of state.
  4. Assign responsibilities/methods (issue, return, renew) — behavior.
  5. Identify relationships: association (Member uses Loan), aggregation (Library aggregates Book), composition (Loan composes DueDate value).
  6. Apply principles: prefer composition over inheritance when behavior varies independently; ensure high cohesion and low coupling.

Formulas

  • self.attribute = value — set instance attribute inside methods.
  • obj = ClassName(args) — create an object (instantiate a class).
  • obj.method(args) — message passing: call a method on an object.
  • @property / def name(self): ... — define a getter property for controlled access.
  • @name.setter / def name(self, value): ... — define a setter for validation.
  • @classmethod / def from_(cls, ...): — class method; first parameter is cls.
  • @staticmethod / def util(...): — static method; no self/cls.
  • class Sub(Base): — inheritance (see topic “Inheritance and polymorphism in Python”).
  • def __str__(self): — string representation for users; return a human-readable string.
  • def __repr__(self): — unambiguous representation for developers; often evaluable or detailed.
  • Duck typing protocol example: def area(shape): return shape.area() — any shape with an area() method works.
  • Composition pattern: class A: def __init__(self): self.b = B() — A creates/owns B.

Worked examples

Example 1: Encapsulation with properties and representation methods Program:

class BankAccount:
    def __init__(self, owner, opening_balance=0.0):
        self.owner = owner                 # public by convention
        self.__balance = float(opening_balance)  # name-mangled (private by convention)

    @property
    def balance(self):
        return self.__balance

    @balance.setter
    def balance(self, value):
        if value < 0:
            raise ValueError("Balance cannot be negative")
        self.__balance = float(value)

    def deposit(self, amount):
        if amount <= 0:
            raise ValueError("Deposit must be positive")
        self.__balance += float(amount)

    def withdraw(self, amount):
        if amount <= 0:
            raise ValueError("Withdrawal must be positive")
        if amount > self.__balance:
            raise ValueError("Insufficient funds")
        self.__balance -= float(amount)

    def __str__(self):
        return f"BankAccount(owner={self.owner}, balance=₹{self.__balance:.2f})"

    def __repr__(self):
        return f"BankAccount(owner={self.owner!r}, opening_balance={self.__balance!r})"

# Demo
acct = BankAccount("Asha", 1000)
acct.deposit(250)
acct.withdraw(400)
print(acct)           # human-friendly
print(repr(acct))     # developer-friendly
print(acct.balance)   # property getter
try:
    acct.balance = -10
except ValueError as e:
    print("Error:", e)

Exact output:

BankAccount(owner=Asha, balance=₹850.00)
BankAccount(owner='Asha', opening_balance=850.0)
850.0
Error: Balance cannot be negative

Example 2: Composition vs. inheritance (prefer composition for parts) Program:

class Engine:
    def __init__(self, displacement_l):
        self.displacement_l = float(displacement_l)
        self._running = False

    def start(self):
        self._running = True

    def stop(self):
        self._running = False

    def status(self):
        return "running" if self._running else "stopped"

class Car:  # Car composes Engine
    def __init__(self, make, model, displacement_l):
        self.make = make
        self.model = model
        self.engine = Engine(displacement_l)  # strong ownership

    def ignite(self):
        self.engine.start()

    def park(self):
        self.engine.stop()

    def __str__(self):
        return f"{self.make} {self.model} (engine {self.engine.displacement_l}L, {self.engine.status()})"

# Demo
c = Car("Tata", "Punch", 1.2)
print(c)
c.ignite()
print(c)
c.park()
print(c)

Exact output:

Tata Punch (engine 1.2L, stopped)
Tata Punch (engine 1.2L, running)
Tata Punch (engine 1.2L, stopped)

Example 3: Polymorphism via duck typing (common interface without inheritance details) Program:

class Rectangle:
    def __init__(self, w, h):
        self.w = float(w)
        self.h = float(h)
    def area(self):
        return self.w * self.h

class Circle:
    def __init__(self, r):
        self.r = float(r)
    def area(self):
        pi = 3.141592653589793
        return pi * self.r * self.r

# Function uses any object with area()
def total_area(shapes):
    s = 0.0
    for sh in shapes:
        s += sh.area()
    return s

rect = Rectangle(3, 4)
circ = Circle(2)
print(f"Rectangle area = {rect.area():.2f}")
print(f"Circle area = {circ.area():.2f}")
print(f"Total area = {total_area([rect, circ]):.2f}")

Exact output:

Rectangle area = 12.00
Circle area = 12.57
Total area = 24.57

Common mistakes

  • Treating Python’s double underscore as true private like in C++/Java. It is name-mangling by convention; access is still possible via _ClassName__attr.
  • Overusing inheritance where composition suffices, leading to tight coupling and broken LSP.
  • Not defining str/repr, making debugging and outputs unclear.
  • Violating invariants in setters or constructors (e.g., allowing negative balances).
  • Assuming @staticmethod can access class or instance state; it cannot.
  • Writing polymorphic functions but then doing explicit type checks, defeating duck typing.

For your exam

  • Diagrams: UML-style class and relationship markers. Full-marks: correctly drawn class compartments, labeled visibility (+/− by convention), correct diamonds/arrows, and a brief caption.
  • Programs: small classes showing encapsulation, composition, or polymorphism. Full-marks: correct syntax, runs without error, clean output, and comments on why design matches the concept.
  • Design reasoning: choose composition over inheritance; apply SRP/OCP/LSP; justify low coupling/high cohesion. Full-marks: state the principle, apply to scenario, explain benefits.

Quick check

  1. Define encapsulation and give one Python feature that supports it.
  2. What is the difference between aggregation and composition?
  3. In Python, what does @classmethod change about the first parameter, and when is it used?

Answers: 1) Encapsulation bundles data with methods and controls access; supported by properties and name-mangling. 2) Aggregation is a whole–part where parts can exist independently; composition is a stronger whole–part where the whole controls part lifetime. 3) It makes the first parameter cls (the class), used for class-level operations or alternate constructors.

Finished this topic? Mark it so your progress, study plan and readiness keep up.

Stuck on something here?