Programming paradigms
Ask four programmers to find Tavren’s available lanterns and you may get four different programs: a loop, a set of objects, processor instructions, or facts and a question. Each is a programming paradigm, a style of organising and expressing a solution. The loops you already write are procedural.
Four ways to express the same work
Each style leaves its own marks in the code. Be able to name each paradigm and recognise its code.
In words, what gives each style away when it does Tavren’s lantern work:
| Paradigm | How it expresses Tavren’s work |
|---|---|
| Imperative / procedural | An ordered sequence changes variables; procedures and functions group the steps. A loop checks each lantern and appends matches. |
| Object-oriented | Classes combine state and operations. Each lantern object stores its own status and exposes methods that read or change it. |
| Low-level | Instructions use a processor’s operations, registers and addresses. A selection loop becomes loads, comparisons and branches. |
| Declarative | Facts and rules describe relationships. A goal asks which lanterns satisfy compatibility and availability conditions. |
A language can support more than one approach
- Python can express the procedural loop and the object design.
- Using a function alone does not make a program object-oriented: the class design must connect state with behaviour.
The design, step by step
Tavren’s lanterns are built as objects in three steps:
1 Which paradigm groups data and methods together in classes?
2 Which paradigm states facts and rules, then asks a goal?
3 Which paradigm works with registers, addresses and branches?
- 1object-oriented
- 2declarative
- 3low-level
Classes and instances
Every one of Tavren’s lanterns has its own ID and status, yet each is read and changed in exactly the same ways. So the design is written once and used for them all. That design is a class; each lantern made from it while the program runs is an object, or instance.
a = Lantern(31, 6) b = Lantern(14, 9) a.SetStatus("on-loan") print(a.GetStatus()) print(b.GetStatus())
Follow each name along its arrow. a and other end at the same lantern; b ends at a separate one, so a change made through a never reaches b.
One class, separate objects
- 1The output is on-loan, then available.
- 2Both objects offer
GetStatus()andSetStatus(). The object before the dot decides whose state the method uses. - 3Changing a leaves b unchanged.
other = a gives another reference to a; it does not instantiate a second lantern. other.SetStatus("repair") would also change the status read through a.1 After the code above, b.SetStatus("repair") runs. What does a.GetStatus() return?
2 Then other = a and other.SetStatus("repair") run. What does a.GetStatus() return now?
3 How many Lantern objects exist after a = Lantern(31, 6), b = Lantern(14, 9) and other = a?
- 1on-loan: b’s change does not touch a
- 2repair: other and a refer to the same object
- 32
Encapsulation, getters and setters
If any code could write to a lantern’s status, one typing slip could store nonsense. Encapsulation keeps an object’s data with the methods that use it and controls access to that data. Tavren changes a status only through a method, so an invalid status cannot get in that way.
class Lantern: # ID, Watts: INTEGER; Status: STRING def __init__(self, lantern_id, watts): self.__ID = lantern_id self.__Watts = watts self.__Status = "available" def GetStatus(self): return self.__Status def SetStatus(self, status): if status not in ("available", "on-loan", "repair"): return False self.__Status = status return True
- A setter changes an attribute. SetStatus accepts one new status and returns whether the update succeeded.
- A getter returns the stored value without changing it.
How callers reach the private data
Outside code never touches the data directly. Be able to say what happens to each call.
Now make both calls and see what the caller gets back each time.
a = Lantern(31, 6) print(a.SetStatus("repair")) print(a.SetStatus("missing")) print(a.GetStatus())
Output: True, False, repair. The invalid update returns False and leaves the stored status unchanged.
Attributes, methods and properties
- An attribute stores data; a method is an operation.
- A property can expose an attribute through getter/setter access. These listings use explicit methods, not Python’s property syntax.
__Status uses Python name mangling to discourage accidental outside access. It is not a security barrier. A setter is needed only for data the requirements allow to change.1 c = Lantern(8, 6) then print(c.SetStatus("lost")). What is printed?
2 What does c.GetStatus() return after that?
3 Why does Lantern have no SetID method?
- 1False
- 2available: the rejected value was never stored
- 3a lantern’s ID must never change, so no method is offered to change it
Constructors and methods
A new lantern should never exist without its ID and wattage. A constructor runs when an object is created, so it sets them at once. Its parameters give the starting values; the object’s attributes keep those values after the constructor finishes.
class Lantern: # ID, Watts: INTEGER; Status: STRING def __init__(self, lantern_id, watts): self.__ID = lantern_id self.__Watts = watts self.__Status = "available"
What self refers to
Follow each argument along its arrow: into a parameter first, then into the new object, which a ends up referring to.
- 1For
a = Lantern(31, 6), Python passes the new object asself. - 231 goes into
lantern_idand 6 intowatts; the constructor stores them inself.__IDandself.__Watts. - 3A parameter is local to the call; the attribute is what the object keeps.
Once the object exists, each later call supplies only what that method needs:
| Call and caller-supplied parameters | Result |
|---|---|
Lantern(31, 6) · ID and wattage | A new reference assigned to a; status starts available. |
a.GetWatts() · none | The integer 6 is returned. |
a.SetStatus("on-loan") · new status | State changes; Boolean True is returned. |
The same class in pseudocode
Pseudocode spells out what Python leaves unsaid: each attribute’s type and access level.
| Notation | Role |
|---|---|
| CLASS Lantern … ENDCLASS | Encloses a class definition. |
| PRIVATE ID : INTEGER | Declares a private attribute and its type. |
| PUBLIC PROCEDURE NEW(Number : INTEGER, Power : INTEGER) | Begins the constructor; assign parameters to attributes before ENDPROCEDURE. |
| a ← NEW Lantern(31, 6) | Creates a new instance and assigns its reference to a. |
Access levels are PRIVATE or PUBLIC when relevant. Methods use the object identifier and a dot, as in a.GetWatts().
1 b = Lantern(22, 12). What does b.GetWatts() return?
2 What status does every new Lantern start with?
3 Write the pseudocode that creates lantern 19 with 9 W and assigns it to c.
- 112
- 2available
- 3
c ← NEW Lantern(19, 9)
Designing classes from requirements
Before anyone types class Lantern, someone decides what a lantern must remember and what staff may do to it. Tavren’s rules: each ID and wattage is fixed, staff read both, and the status may change to available, on-loan or repair. Each rule becomes a member of the class.
A class diagram has three compartments: name, attributes, methods. The black numbers tie each member to the requirement it serves.
− ID : INTEGER
− Watts : INTEGER
− Status : STRING
+ NEW(number : INTEGER, watts : INTEGER)
+ GetID() : INTEGER
+ GetWatts() : INTEGER
+ GetStatus() : STRING
+ SetStatus(status : STRING) : BOOLEAN
+ SupplyDetails() : STRING
- − means private; + means public.
- Top compartment: the class name. Middle: attributes and types. Bottom: methods, parameters and result types.
Turn each requirement into members
Each numbered requirement matches the members with the same number in the diagram.
| Requirement | Design consequence |
|---|---|
| 1 Identify a lantern permanently | ID is an INTEGER initialised by the constructor; GetID returns it. No SetID method is exposed. |
| 2 Keep a fixed wattage | Watts is an INTEGER initialised by the constructor; GetWatts returns it. |
| 3 Control changing hire state | Status is a STRING. GetStatus reads it; SetStatus checks and updates it. |
| 4 Describe the supply | SupplyDetails returns a STRING; specialised classes can redefine it. |
1 Which members of Lantern are private?
2 Why is there no SetWatts method?
3 What type does SetStatus return, and why?
- 1ID, Watts and Status
- 2the wattage is fixed, so nothing may change it after the constructor
- 3BOOLEAN: it tells the caller whether the update was accepted
Inheritance
Some of Tavren’s lanterns run on batteries, and writing a whole new class for them would copy every method. Inheritance derives a more specialised subclass from a superclass (base or parent class). A BatteryLantern is a Lantern: it reuses lantern operations and adds a battery runtime.
BatteryLantern lists only what it adds; the hollow triangle brings in everything else from Lantern. Object c shows both parts together in one lantern.
class BatteryLantern(Lantern): # Runtime: INTEGER, in hours def __init__(self, lantern_id, watts, runtime): super().__init__(lantern_id, watts) self.__Runtime = runtime def GetRuntime(self): return self.__Runtime
How the subclass constructor works
- 1
super().__init__(lantern_id, watts)calls the parent constructor. It sets ID, Watts and Status for this same object. - 2The next line sets Runtime, the attribute the subclass adds.
- 3Inherited getters read the parent’s private attributes; the subclass does not access them directly.
Pseudocode names the parent in the class header and calls its constructor through SUPER:
| 2026 pseudocode notation | Meaning |
|---|---|
| CLASS BatteryLantern INHERITS Lantern | Names the subclass and its parent. |
| SUPER.NEW(Number, Power) | Calls the parent constructor from the subclass constructor. |
| Runtime ← Hours | Initialises the subclass’s additional attribute. |
1 d = BatteryLantern(19, 9, 4). What do d.GetWatts() and d.GetRuntime() return?
2 What does d.GetStatus() return, and which constructor set it?
3 In a class diagram, which way does the hollow triangle point?
- 19 and 4
- 2available: set by the Lantern constructor, called through super()
- 3towards the parent (superclass)
Polymorphism
A battery lantern and a mains lantern describe their power supply differently, yet a caller should ask both the same way. Polymorphism lets the same method name behave differently in derived classes. The object’s actual class decides which version runs.
class BatteryLantern(Lantern): # Runtime: INTEGER, in hours def __init__(self, lantern_id, watts, runtime): super().__init__(lantern_id, watts) self.__Runtime = runtime def GetRuntime(self): return self.__Runtime def SupplyDetails(self): return str(self.__Runtime) + " hours on battery"
The parent’s SupplyDetails method returns "external supply". The subclass defines the same method name and returns a description using its own runtime.
devices = [Lantern(31, 6), BatteryLantern(27, 12, 6)] for item in devices: print(item.GetID(), item.SupplyDetails())
One call, a different version per class
Follow item.SupplyDetails() down each branch, once for each object in the list.
| Actual class | Result of item.SupplyDetails() |
|---|---|
| Lantern | external supply · the parent implementation. |
| BatteryLantern | 6 hours on battery · the override reads its stored runtime. |
- Inheriting the method unchanged reuses its behaviour. Overriding it gives the specialised behaviour while the caller keeps the same call.
- Changing an attribute’s value alone is not this form of polymorphism.
1 What does BatteryLantern(19, 9, 4).SupplyDetails() return?
2 What does Lantern(8, 6).SupplyDetails() return?
3 The override is deleted from BatteryLantern. What does BatteryLantern(19, 9, 4).SupplyDetails() return now?
- 1"4 hours on battery"
- 2"external supply"
- 3"external supply": the inherited parent method runs
Containment and aggregation
A customer’s hire is made up of lanterns, but a hire is not itself a lantern, so inheritance is the wrong tool. Containment / aggregation is a has-a relationship: a hire holds references to lantern objects that already exist.
Read the diagram as “a Hire has Lanterns”: the hollow diamond sits at the Hire end. The Hire class keeps those references in a list.
class Hire: def __init__(self, hire_id): self.__ID = hire_id self.__Lanterns = [] def AddLantern(self, lantern): self.__Lanterns.append(lantern) def GetLantern(self, index): return self.__Lanterns[index]
Run the caller and follow hire.GetLantern(0): it reaches the same Lantern 31 that a names.
a = Lantern(31, 6) b = Lantern(22, 12) hire = Hire("evening") hire.AddLantern(a) hire.AddLantern(b) hire.GetLantern(0).SetStatus("on-loan") print(a.GetStatus())
Store a reference, not a copy
- Each new Hire constructs its own empty list.
- Lantern objects can exist before the hire and stay in the wider stock system afterwards.
1 A hire holds a then b, with b = Lantern(22, 12). What does hire.GetLantern(1).GetID() return?
2 Then hire.GetLantern(1).SetStatus("repair") runs. What does b.GetStatus() return?
3 Hire and Lantern: is-a or has-a? BatteryLantern and Lantern?
- 122
- 2repair: the list holds a reference to b itself
- 3Hire has Lanterns (aggregation); BatteryLantern is a Lantern (inheritance)
Loading objects from files
Objects vanish when the program stops, so each run builds them again from the stock file. Each record read from a file becomes a new object. The loader returns an array of references, so later code can select through getters.
Lanterns.txt holds one ID|Wattage|Status record per line. The job is to turn each line into a Lantern object.
31|6|available 14|9|on-loan 27|12|repair 8|6|available 22|12|available 19|9|on-loan
Read the loop body: each pass splits one line and constructs a fresh Lantern from its fields.
def ReadLanterns(filename): lanterns = [] try: with open(filename) as source: for line in source: fields = line.strip().split("|") number, watts, status = fields item = Lantern(int(number), int(watts)) item.SetStatus(status) lanterns.append(item) except OSError: print("Cannot read lantern file") return [] return lanterns stock = ReadLanterns("Lanterns.txt")
One line, one new object
Every line must give a lantern of its own. Be able to say what each array element refers to.
Test a missing file too
stock = ReadLanterns("Missing.txt") print("Loaded:", len(stock))
- Output: Cannot read lantern file, then Loaded: 0.
- If opening or reading raises OSError, the handler returns an empty array, not a partly loaded one.
- The
withstatement closes an opened file on success or failure.
1 How many Lantern objects does ReadLanterns("Lanterns.txt") create?
2 What does it return when the file is missing?
3 The line item = Lantern(...) is moved above the loop. What goes wrong?
- 16, one per line
- 2an empty array, after printing Cannot read lantern file
- 3every element refers to the same single object, so there are no separate lanterns
Selecting objects from arrays
A customer wants an available lantern of at least 9 W. Keep only the objects that meet both criteria, then output their count and details using getters.
Staff enter a required hire status and a minimum wattage. ReadLanterns loads the six lanterns from Lanterns.txt.
Lanterns.txt holds ID/watts/status records: 31/6/available; 14/9/on-loan; 27/12/repair; 8/6/available; 22/12/available; 19/9/on-loan.
SelectLanterns does the filtering. It asks each object for its status and watts through getters and keeps the ones that pass both tests.
def SelectLanterns(lanterns, wanted_status, minimum_watts): selected = [] for item in lanterns: if (item.GetStatus() == wanted_status and item.GetWatts() >= minimum_watts): selected.append(item) return selected
The main program reads the two criteria, hands the whole stock to SelectLanterns, then reports what comes back.
print("Enter status") wanted_status = input().lower() print("Enter minimum watts") minimum = int(input()) stock = ReadLanterns("Lanterns.txt") matches = SelectLanterns(stock, wanted_status, minimum) print("Matches:", len(matches)) for item in matches: print(item.GetID(), item.GetWatts(), item.GetStatus())
Enter status Enter minimum watts Matches: 1 22 12 available
Each object tested against both criteria
Inputs available and 9. The status test runs first; the watts test only if it passes.
| Status | Watts | Status test | Watts test | Result | |
|---|---|---|---|---|---|
| ID 31 | available | 6 | yes | no | rejected: 6 W is under 9 |
| rejected: 6 W is under 9 | |||||
| ID 14 | on-loan | 9 | no | — | rejected: status is on-loan |
| rejected: status is on-loan | |||||
| ID 27 | repair | 12 | no | — | rejected: status is repair |
| rejected: status is repair | |||||
| ID 8 | available | 6 | yes | no | rejected: 6 W is under 9 |
| rejected: 6 W is under 9 | |||||
| ID 22 | available | 12 | yes | yes | kept: both tests pass |
| kept: both tests pass | |||||
| ID 19 | on-loan | 9 | no | — | rejected: status is on-loan |
| rejected: status is on-loan | |||||
What the selection stores
- Only ID 22 is available and at least 9 W. ID 27 has enough power but is in repair.
selected.append(item)stores the existing reference: both arrays refer to the same lantern. No object is created or copied.- For inputs repair, 9, only ID 27 matches. For available, 13, the count is 0 and the loop prints no details.
1 The inputs are on-loan and 9. Which IDs match, and what count is printed?
2 The inputs are available and 6. Which IDs match?
3 Does matches hold copies of the lanterns?
- 114, 19: Matches: 2
- 231, 8, 22
- 3no: it holds references to the same objects as stock
Testing the object model
A class can run yet mix up two lanterns, so test it through its public methods. Each result should show one thing: separate instances, rejected changes, inherited members or overridden behaviour.
Each test aims at one thing that could go wrong. The last column says what a failure would tell you.
| Test | Expected result | What a failure exposes |
|---|---|---|
| Create a(31, 6) and b(14, 9); set only a to on-loan | a is on-loan; b stays available | Shared state or the wrong receiver. |
| Attempt status missing after repair | False; status stays repair | An update performed before validation. |
| Create BatteryLantern(27, 12, 6) | GetID = 27; GetWatts = 12; Runtime = 6 | Parent constructor omitted or parameters misplaced. |
| Call SupplyDetails on both classes | external supply / 6 hours on battery | Missing override or an incorrect method name. |
| Store a in a Hire; change through the hire | Reading a shows the changed status | An accidental copy rather than a shared reference. |
The same tests as assertions: the message prints only if every one holds.
a = Lantern(31, 6) b = Lantern(14, 9) assert a.SetStatus("repair") assert not a.SetStatus("missing") assert a.GetStatus() == "repair" assert b.GetStatus() == "available" c = BatteryLantern(27, 12, 6) assert c.GetWatts() == 12 assert c.SupplyDetails() == "6 hours on battery" print("object checks passed")
Which relationship for which requirement
Each requirement calls for one of these; be able to choose.
| Use | For |
|---|---|
| class | one lantern’s state and operations |
| instances | distinct physical lanterns |
| inheritance | a specialised lantern |
| polymorphism | one shared call with specialised behaviour |
| aggregation | a hire containing existing lanterns |
1 Which test in the table would catch a missing override?
2 A hire must hold lanterns that already exist. Which relationship do you use?
3 What happens when an assertion’s condition is false?
- 1calling SupplyDetails on both classes
- 2aggregation (containment)
- 3the program stops with an AssertionError, so the test fails