Skip to main content
CodeOath

Chapter 1 · About 12 minFree

Classes, objects and the four pillars

Learn classes and objects, and the four pillars of object-oriented design, in Python, using the stock and billing system of a small pharmacy chain.

Published by Hem Mankad, founder of CodeOath and a software engineer for more than eight years. Prepared with AI assistance.

Meet Marigold Medicals

Marigold Medicals is a chain of four medical stores in Nashik. Sunanda Patil owns it. Each store has a counter with a tablet, a thermal printer for bills, and a pharmacist who knows the regulars by name. Stock arrives from a distributor every Tuesday. Until last year, every store kept its stock in a notebook and Sunanda added up four notebooks on Sunday night.

Nikhil Deshmukh is a final-year computer engineering student. He is spending one semester as an intern at Marigold Medicals, building the stock and billing system: an app on each counter tablet, and one small Linux server rented in a Pune data centre that holds the stock of all four stores. Sunanda, Nikhil, the stores and every number in this track are invented to teach with. Nothing here describes a real company.

Every chapter of this track follows the same system. The first two chapters shape the code in classes. The next two put the stock into a database. Chapters 5 and 6 look at what the server's operating system does when the stock service, the backup job and the web server all want the processor and the memory at once. The last two follow one tap on a tablet across the network to the server and back. One system, eight chapters, so that each idea is met where it is actually used.

The code is Python 3.14. The ideas carry straight to Java, C# and C++, which is where many campus interviews ask about them, so here are the words side by side:

PythonJava or C#Meaning
class Medicine:class Medicine { }a plan for objects
__init__constructorruns when an object is made
selfthisthe object the method was called on
_stock (convention)private int stock;a field other code should not touch
class Base(ABC) with @abstractmethodinterface or abstract classa promise of methods, no body

Every code block in this chapter was run, in order, and the output shown is what it printed.

A class is a plan, an object is one thing made from it

Nikhil's first job is to describe a medicine so the program can hold one. A class is the description. An object is one actual thing built from it, with its own values.

class Medicine:
    gst_rate = 12          # shared by every Medicine, a class attribute

    def __init__(self, name, mrp, stock):
        self.name = name   # instance attributes: this object's own values
        self.mrp = mrp
        self.stock = stock

    def __repr__(self):
        return f"Medicine({self.name!r}, mrp={self.mrp}, stock={self.stock})"

crocin = Medicine("Paracetamol 500 mg", 30, 120)
cetzine = Medicine("Cetirizine 10 mg", 18, 40)
print(crocin)
print(cetzine)
print(crocin.gst_rate, cetzine.gst_rate, Medicine.gst_rate)

Output:

Medicine('Paracetamol 500 mg', mrp=30, stock=120)
Medicine('Cetirizine 10 mg', mrp=18, stock=40)
12 12 12

Three things to see. __init__ runs when Medicine(...) is called and fills in the new object. self is the object being filled in; Python passes it for you, which is why the call has three arguments and the method lists four. And gst_rate is written once, at class level, so every medicine shares it. The MRP (maximum retail price) and the stock belong to each object, because they differ from one medicine to the next. The GST rates in this track are assumed figures for the example, not a statement of the tax law.

The interview question behind this section is "what is the difference between a class and an object", and the answer is in the code: one class, two objects, each with its own name, mrp and stock. A follow-up is "what is the difference between a class attribute and an instance attribute". A class attribute lives on the class and is shared. An instance attribute lives on one object. Change Medicine.gst_rate and both medicines see the change. Change crocin.mrp and only that object changes.

__repr__ is not one of the pillars, but it is the first method worth writing in any class. Without it, print(crocin) shows a memory address. With it, every print and every error message tells you which object you are looking at.

Encapsulation: the stock count has one door

Here is what went wrong in week two. A bill for 130 strips of paracetamol was keyed in when 120 were on the shelf, and the program happily did this:

crocin.stock = crocin.stock - 130
print(crocin.stock)

Output:

-10

A negative stock is not a medicine. It is a bug waiting to spread into every report. The cause is that any line of code, anywhere, can write stock directly. Encapsulation is the fix: keep the data behind methods, so the only way to change the count is through code that checks the rule.

class Medicine:
    gst_rate = 12

    def __init__(self, name, mrp, stock):
        self.name = name
        self.mrp = mrp
        self._stock = stock            # the underscore says: not for outside use

    @property
    def stock(self):                   # read-only view from outside
        return self._stock

    def sell(self, qty):
        if qty <= 0:
            raise ValueError("quantity must be positive")
        if qty > self._stock:
            raise ValueError(f"only {self._stock} of {self.name} in stock")
        self._stock -= qty

    def receive(self, qty):
        if qty <= 0:
            raise ValueError("quantity must be positive")
        self._stock += qty

crocin = Medicine("Paracetamol 500 mg", 30, 120)
crocin.sell(20)
print(crocin.stock)
try:
    crocin.sell(130)
except ValueError as e:
    print("refused:", e)

Output:

100
refused: only 100 of Paracetamol 500 mg in stock

Now the stock has one door in (receive) and one door out (sell), and the rule "stock never goes below zero" lives in exactly one place. That is the point of encapsulation. It is not about secrecy. It is about keeping a rule next to the data it protects, so that the rule cannot be forgotten by the caller.

Python does not enforce privacy. A single underscore is a convention: "this is internal, touch it and you own the consequences". Java and C# have private, and the compiler refuses outside access. Interviewers who ask "how do you make a field private in Python" want the convention named, and a double underscore (__stock) mentioned as the stronger form that mangles the name. The @property line turns the method stock into something read like an attribute, so callers write crocin.stock and cannot assign to it. Try crocin.stock = 5 and Python raises AttributeError, because no setter was defined.

Abstraction: the counter does not know how the printer works

Two of the four stores have a thermal printer. The other two, for now, save the bill as a PDF and the pharmacist sends it on WhatsApp. The billing code should not care which. That is abstraction: show the operation, hide the mechanism.

from abc import ABC, abstractmethod

class BillPrinter(ABC):
    @abstractmethod
    def print_bill(self, text):
        ...

class ThermalPrinter(BillPrinter):
    def print_bill(self, text):
        print("[thermal]", text.replace("\n", " | "))

class PdfPrinter(BillPrinter):
    def __init__(self, folder):
        self.folder = folder
    def print_bill(self, text):
        print(f"[pdf saved in {self.folder}]", text.replace("\n", " | "))

def checkout(printer, lines):
    text = "\n".join(lines)
    printer.print_bill(text)       # one call; which machine answers is not this function's business

checkout(ThermalPrinter(), ["Marigold Medicals, Panchavati", "Paracetamol 500 mg x 2  60"])
checkout(PdfPrinter("/bills/deolali"), ["Marigold Medicals, Deolali", "Cetirizine 10 mg x 1  18"])
try:
    BillPrinter()
except TypeError as e:
    print("cannot build:", e)

Output:

[thermal] Marigold Medicals, Panchavati | Paracetamol 500 mg x 2  60
[pdf saved in /bills/deolali] Marigold Medicals, Deolali | Cetirizine 10 mg x 1  18
cannot build: Can't instantiate abstract class BillPrinter without an implementation for abstract method 'print_bill'

checkout knows one thing about printers: they have print_bill. The abstract class BillPrinter writes that promise down, and Python refuses to build a BillPrinter directly because the promise has no body. When Sunanda buys thermal printers for the other two stores, the only change is which printer object the store is given. checkout is untouched.

The question "what is the difference between abstraction and encapsulation" is a standard question, and the two sections above are the answer. Encapsulation hides the data behind methods so a rule cannot be bypassed. Abstraction hides the mechanism behind an operation so the caller can stay simple. The first keeps a rule next to the data it protects, so that nothing can bypass it. The second lets a caller use an operation without knowing how it is done.

Inheritance: a scheduled drug is a medicine with one extra rule

Some medicines can be sold only against a prescription. Nikhil needs a type that is a medicine in every way, plus one extra check. Inheritance is for exactly this: a new class that takes everything from an existing one and changes or adds a little.

class PrescriptionMedicine(Medicine):
    def __init__(self, name, mrp, stock, schedule):
        super().__init__(name, mrp, stock)     # let Medicine set up the shared part
        self.schedule = schedule

    def sell(self, qty, prescription=None):
        if prescription is None:
            raise ValueError(f"{self.name} is schedule {self.schedule}: prescription required")
        super().sell(qty)                      # then the normal stock rule

amoxy = PrescriptionMedicine("Amoxicillin 500 mg", 95, 30, "H")
print(isinstance(amoxy, Medicine), isinstance(crocin, PrescriptionMedicine))
try:
    amoxy.sell(2)
except ValueError as e:
    print("refused:", e)
amoxy.sell(2, prescription="RX-4471")
print(amoxy.stock)

Output:

True False
refused: Amoxicillin 500 mg is schedule H: prescription required
28

PrescriptionMedicine did not repeat the stock rule. It called super().sell(qty) after its own check, so the rule is still written once, in Medicine. That is the honest use of inheritance: the child is a parent, with a difference. A prescription medicine is a medicine. Ask the is-a question out loud before you inherit. If the sentence sounds wrong ("a store is a medicine"), inheritance is the wrong tool, and the next chapter shows what to use instead.

isinstance(amoxy, Medicine) is True because a child object counts as its parent type everywhere the parent is accepted. A list of Medicine can hold amoxy. A function that takes a Medicine can take amoxy. That property is what makes the fourth pillar possible.

Two words interviewers use here. Overriding is what sell did: the child defines a method with the same name and replaces the parent's version. Overloading is two methods with the same name and different parameter lists in one class. Java has it. Python does not; a Python method with an optional parameter, like prescription=None above, is the usual replacement. Say that plainly if asked, rather than claiming Python overloads.

Polymorphism: one call, the right behaviour

The counter sells more than medicines. It sells sunscreen, baby wipes and glucose biscuits, which carry a different GST rate in this example. Nikhil wants the bill loop to add up a mixed basket without a chain of if statements asking what each item is.

class Cosmetic:
    gst_rate = 18

    def __init__(self, name, mrp, stock):
        self.name = name
        self.mrp = mrp
        self._stock = stock

    @property
    def stock(self):
        return self._stock

    def sell(self, qty):
        if qty <= 0 or qty > self._stock:
            raise ValueError(f"cannot sell {qty} of {self.name}")
        self._stock -= qty

def line_total(item, qty):
    base = item.mrp * qty
    return base, base * item.gst_rate / 100

basket = [(crocin, 2), (Cosmetic("Sunscreen SPF 30", 250, 15), 1), (amoxy, 1)]
grand = 0
for item, qty in basket:
    base, gst = line_total(item, qty)
    grand += base + gst
    print(f"{item.name:22} x{qty}  {base:6.2f}  gst {gst:5.2f}  ({item.gst_rate}%)")
print(f"total {grand:.2f}")

Output:

Paracetamol 500 mg     x2   60.00  gst  7.20  (12%)
Sunscreen SPF 30       x1  250.00  gst 45.00  (18%)
Amoxicillin 500 mg     x1   95.00  gst 11.40  (12%)
total 468.60

Check the arithmetic once by hand: 60 plus 7.20 is 67.20; 250 plus 45 is 295; 95 plus 11.40 is 106.40; the sum is 468.60. The loop never asked "is this a cosmetic". It asked each item for its gst_rate and mrp, and each item answered in its own way. That is polymorphism: one call, many behaviours, decided by the object, not by the caller.

Notice that Cosmetic does not inherit from Medicine. It has the same method names and attributes, and in Python that is enough. This is called duck typing: if it has mrp, gst_rate and sell, the loop can use it. Java needs the shared names to be declared in a common interface or parent class first, which is one reason interviews there ask you to draw a class diagram before you write the loop. The next chapter builds that shared interface properly and shows when to prefer composition to inheritance.

The test for whether polymorphism is doing its job: can you add a new kind of item without editing the loop? Add a Device class for a digital thermometer, with its own rate, and the loop above prints it correctly with no change. If you find yourself writing if isinstance(item, Cosmetic) inside the loop, the behaviour has leaked out of the object and into the caller, and the fourth pillar has been lost.

The four pillars on one bill

Here is the whole thing in one place, the way to say it in a round, with the Marigold example for each:

PillarOne sentenceIn this chapter
EncapsulationData and the rules that protect it live together, behind methods_stock is changed only by sell and receive, which refuse a negative count
AbstractionThe caller sees an operation, not a mechanismcheckout calls print_bill; thermal or PDF is the printer's business
InheritanceA child type is a parent type with a differencePrescriptionMedicine is a Medicine plus one check, and reuses sell through super()
PolymorphismOne call, the behaviour chosen by the objectThe bill loop asks each item for gst_rate and never checks its type

A few habits that follow from the chapter. Write __repr__ first. Put every rule about a field next to that field, behind a method. Before inheriting, say the is-a sentence aloud. When a loop starts checking types, move the behaviour into the objects. And when an interviewer asks for a pillar, give the one-sentence version and then an example you have actually written; the second half is what they remember.

What this chapter did not cover is how to declare the shared shape of Medicine and Cosmetic so that a mistake is caught before the bill loop runs, what to do when a store has printers and bills rather than is one, and the handful of class questions that follow the four pillars: __eq__, __hash__, static methods, class methods, and multiple inheritance. That is chapter 2. Chapter 3 then takes the same medicines and batches off the tablet and into the database on the Pune server.

Coming: the guide answers questions in a later release.