Python OOP Practice: Design a Bank, an Employee System and a Library
Put every OOP tool to work on three small systems: online banking, employee management and a library. Design first with five questions, prompt with Role, Context, Task and Format, then check the result line by line.
What you will learn
- Design a system with five questions: nouns, verbs, attributes, relationships and what is abstract
- Write a Role, Context, Task, Format prompt for an OOP system
- Read AI-written code against every requirement, not just whether it runs
- Map each design need to the right OOP tool
Before you start
- Inheritance, composition and abstract classes in Python
- Dataclasses, properties and special methods
You've seen each OOP tool on its own, one at a time. In real programs they show up together, and that's where design starts to matter. This article builds three small systems, a bank, an employee system and a library, and each time it reads the result against what was asked for.
Design first: five questions
Think about building a bookshelf. You wouldn't start by drilling holes. First you list the parts: frame, shelves, screws. Then what you'll do with them: cut, drill, join. Then what describes each part, like its length and colour. Finally, how the parts connect: each shelf sits inside the frame. Code works the same way.
Take this description: "A bank holds accounts. Each account has an owner and a balance. Customers deposit, withdraw and transfer money, and each move is saved as a transaction."
- The nouns become classes: Bank, Account, Transaction.
- The verbs become methods: deposit, withdraw, transfer.
- What describes each thing becomes attributes: owner, balance.
- The relationships pick the tool: is a means inheritance, has a means composition.
- What should be abstract? Account is a general idea, so it becomes an abstract class.
Question four, in code:
class Account:
def __init__(self, owner, balance=0):
self.owner = owner
self.balance = balance
def deposit(self, amount):
self.balance += amount
class SavingsAccount(Account):
pass
class Bank:
def __init__(self):
self.accounts = []
savings = SavingsAccount("Alice")
bank = Bank()
bank.accounts.append(savings)
print(isinstance(savings, Account))
print(isinstance(bank, Account))
print(savings in bank.accounts)
True
False
True
A savings account is an account, so it inherits. A bank isn't an account, but it has accounts, so it holds them in a list. Those five answers give you a class diagram. Draw that first, then write the code or the prompt.
Use case 1: an online banking system
The design asks for an abstract Account with abstract deposit and withdraw, SavingsAccount and CheckingAccount subclasses, a Bank that holds accounts (composition), a Transaction dataclass, a read-only balance property, and special methods so print, len and + work. We ask for it with the four-part prompt from prompting fundamentals:
Role: You are a senior Python developer who teaches clean object-oriented design.
Context: I am learning OOP. I know classes, inheritance, abstract classes, dataclasses and special methods. I want a small online banking system I can read in one sitting.
Task: Build it with an abstract Account class (deposit and withdraw are abstract), SavingsAccount and CheckingAccount subclasses, a Transaction dataclass, a read-only balance property and a Bank class that holds many accounts.
Format: One Python file, standard library only, lines under 60 characters, a short comment above each class, and a few lines at the bottom that open two accounts, transfer money and print the result.
Give this prompt to any AI tool you like and read what you get. You don't have to write it all yourself, but you do have to understand it. Here's one possible result. Yours will look different, and that's fine.
from abc import ABC, abstractmethod
from dataclasses import dataclass
@dataclass
class Transaction:
kind: str
amount: float
class Account(ABC):
def __init__(self, account_id, owner):
self.account_id = account_id
self.owner = owner
self._balance = 0.0
self._transactions = []
@property
def balance(self):
return self._balance
@abstractmethod
def deposit(self, amount):
...
@abstractmethod
def withdraw(self, amount):
...
def _record(self, kind, amount):
item = Transaction(kind, amount)
self._transactions.append(item)
def __len__(self):
return len(self._transactions)
def __add__(self, other):
return self._balance + other._balance
def __str__(self):
name = type(self).__name__
return (f"{name} {self.account_id} | {self.owner}"
f" | ${self._balance:,.2f}")
class SavingsAccount(Account):
def __init__(self, account_id, owner, rate=0.05):
super().__init__(account_id, owner)
self.interest_rate = rate
def deposit(self, amount):
self._balance += amount
self._record("deposit", amount)
def withdraw(self, amount):
if amount > self._balance:
raise ValueError("Insufficient funds")
self._balance -= amount
self._record("withdraw", amount)
def add_interest(self):
self.deposit(self._balance * self.interest_rate)
class CheckingAccount(Account):
def __init__(self, account_id, owner, overdraft=200):
super().__init__(account_id, owner)
self.overdraft = overdraft
def deposit(self, amount):
self._balance += amount
self._record("deposit", amount)
def withdraw(self, amount):
if amount > self._balance + self.overdraft:
raise ValueError("Overdraft limit reached")
self._balance -= amount
self._record("withdraw", amount)
class Bank:
def __init__(self, name):
self.name = name
self._accounts = []
@property
def accounts(self):
return list(self._accounts)
def open_account(self, account):
self._accounts.append(account)
def transfer(self, src, dst, amount):
src.withdraw(amount)
dst.deposit(amount)
def __len__(self):
return len(self._accounts)
def __str__(self):
return f"Bank: {self.name} ({len(self)} accounts)"
bank = Bank("PyBank")
alice = SavingsAccount("SA001", "Alice")
bob = CheckingAccount("CK001", "Bob")
bank.open_account(alice)
bank.open_account(bob)
alice.deposit(1000)
bob.deposit(250)
bank.transfer(alice, bob, 200)
alice.add_interest()
print(bank)
for account in bank.accounts:
print(account)
print("Alice transactions:", len(alice))
print(f"Combined: {alice + bob:,.2f}")
try:
bob.withdraw(1000)
except ValueError as error:
print("Error:", error)
Bank: PyBank (2 accounts)
SavingsAccount SA001 | Alice | $840.00
CheckingAccount CK001 | Bob | $450.00
Alice transactions: 3
Combined: 1,290.00
Error: Overdraft limit reached
Follow the money. Alice deposits 1000 and Bob 250. transfer just calls withdraw on Alice and deposit on Bob, so she has 800 and he has 450. Interest is 5% of 800, which is 40, so Alice reaches 840. Her three transactions come from __len__, and alice + bob gives 1,290 through __add__. Bob's limit is 450 plus a 200 overdraft, so 650, and his withdrawal of 1000 is refused. Both subclasses write withdraw, with a different rule each. That's why the abstract class was worth having.
Read it against what you asked for
This is the step people skip. Running isn't enough; it has to match the prompt, one line at a time. The abstract Account holds: try to create one and Python refuses.
from abc import ABC, abstractmethod
class Account(ABC):
@abstractmethod
def deposit(self, amount):
...
acct = Account()
Traceback (most recent call last):
File "S03L07_Practice\bank_abstract_error.py", line 10, in <module>
acct = Account()
TypeError: Can't instantiate abstract class Account without an implementation for abstract method 'deposit'
The read-only balance holds too:
class Account:
def __init__(self):
self._balance = 100.0
@property
def balance(self):
return self._balance
acct = Account()
print(acct.balance)
acct.balance = 5000
100.0
Traceback (most recent call last):
File "S03L07_Practice\bank_readonly_error.py", line 12, in <module>
acct.balance = 5000
^^^^^^^^^^^^
AttributeError: property 'balance' of 'Account' object has no setter
Now the misses. The Format line asked for a short comment above each class, and this file has none. One more message to the tool fixes it. And the Task line never names special methods. This result has them, but yours might not. That's a gap in the prompt, so add them there.
Use case 2: an employee management system
This one asks for a deeper chain (Person, Employee, then Manager and Developer), a JSON mixin you can attach without changing the chain, a factory method that builds an object from a dictionary, a Project dataclass and a Department that has employees.
Practise differently this time. Don't send one big prompt; build it in steps. Ask for a Person with a name and an age, read it and run it. Then an Employee with a salary that can't be negative. Then a JSON mixin on Manager. Each message is small, so when something breaks you know where. Here are the parts of one possible result that matter most:
class Employee(Person):
_id_counter = 0
def __init__(self, name, age, salary):
super().__init__(name, age)
self.salary = salary
self.employee_id = Employee.generate_id()
@property
def salary(self):
return self._salary
@salary.setter
def salary(self, value):
if value < 0:
raise ValueError("Salary cannot be negative")
self._salary = value
@staticmethod
def generate_id():
Employee._id_counter += 1
return f"EMP{Employee._id_counter:04d}"
@classmethod
def from_dict(cls, data):
return cls(**data)
Running the full file, which builds Maya (Manager, 9000), Ravi (Developer, 6500, one 120-hour project), a Department, then Lena from a dictionary, and finally tries ravi.salary = -1, gives:
Engineering: 2 employees
EMP0001 Maya (Manager)
EMP0002 Ravi (Developer)
Payroll: 15500
Ravi hours: 120
{
"name": "Maya",
"age": 41,
"salary": 9000,
"employee_id": "EMP0001"
}
EMP0003 Lena (Manager)
Error: Salary cannot be negative
The salary setter checks every assignment, including the one in __init__. The static method's counter gives each employee the next number. Manager.from_dict passes Manager in as cls, so Lena is a Manager with number 3. Manager is declared as class Manager(JsonMixin, Employee), so Maya gets to_json and Employee itself didn't change. The chain, the check, the id, the mixin, the project and the payroll are all there. The comments are missing again.
Use case 3: a library management system
Books are dataclasses, members keep a private borrowed list, search comes from a mixin, and len and in come from special methods. Give the prompt to your tool first, before you look at this result. The search mixin only needs self._books, and Library has that:
class SearchMixin:
def search_by_title(self, query):
query = query.lower()
return [b for b in self._books
if query in b.title.lower()]
def search_by_author(self, query):
query = query.lower()
return [b for b in self._books
if query in b.author.lower()]
The run adds Dune, Emma and Persuasion, checks "Dune" in library and "Ulysses" in library, lends Dune to Nina, tries to lend it to Omar, searches for "austen", then returns Dune:
City Library: 3 books
True
False
True
False
Nina has: 1
Emma by Jane Austen [Available]
Persuasion by Jane Austen [Available]
Dune by Frank Herbert [Available]
Nina gets Dune (True). Omar asks for the same book, it isn't available, so he gets False and nothing moves. Nina's count comes from a property over her private list. The library decides, and the member only tracks what she holds.
Compare your result with this one. You'll see different names, maybe an extra class, or another way to search. Every tool and version gives different code. So don't ask which one looks like mine. Ask which one meets the requirements, then which is easier to read. If something's off, tell the tool what to change in one more message.
Four more to practise
- E-commerce: a Product abstract class, a CartItem dataclass and a ShoppingCart. What is a product, and what has items?
- Game characters: a Character base, Warrior and Mage, an Inventory, and attack and defend mixins. Which mixins do both share?
- School: Student and Teacher inherit from Person, with a Course, a GradeBook and a Grade dataclass. What does a course have?
- Smart home: a Device abstract class, Light and Thermostat, a Room, and a mixin that logs every change. What abstract methods should a device have?
One possible cart solution (two copies of Emma at 12.50 and one lamp at 30, a second cart with one more Emma, an out-of-stock lamp, then removing the lamp) prints:
3 55.0
4 67.5
Out of stock: Lamp
2 1
A cheat sheet for every design
RULES = {
"IS-A": "inheritance",
"HAS-A": "composition",
"must implement": "abstract base class",
"mostly data": "dataclass",
"shared extra": "mixin",
"checked access": "property",
"len, in, print": "special methods",
"other ways to build": "classmethod",
}
for need, tool in RULES.items():
print(f"{need:<20}-> {tool}")
IS-A -> inheritance
HAS-A -> composition
must implement -> abstract base class
mostly data -> dataclass
shared extra -> mixin
checked access -> property
len, in, print -> special methods
other ways to build -> classmethod
Each row has its own article: inheritance, composition, abstract classes and dataclasses, mixins, properties and class methods and special methods.
Try it yourself
Write one prompt yourself, without copying these, for any one of the four challenges. Then check what comes back, line by line, against every requirement you wrote.
Related course on Udemy
The Python Architect Masterclass: Full Stack to AI Engineer
Python, Django, FastAPI, React, Docker, AWS, LLMs, RAG, agents and MCP, from first steps to AI engineer.View on Udemy ↗: The Python Architect Masterclass: Full Stack to AI Engineer (paid course, opens in a new tab)Related posts
Python Class Methods, Static Methods and Properties: What Each One Receives
Instance methods get self, class methods get cls, static methods get nothing. Then properties, setters and deleters, with small runnable files and their real output.
Python Classes and Objects: __init__, self and PEP 8 Names
A class is the blueprint and an object is what you build from it. Car, Student, Dog, Circle and BankAccount show what __init__ and self really do, how attribute lookup works, the missing self error, and PEP 8 names.
Python Inheritance and Polymorphism: super(), Overriding and Duck Typing
A child class gets everything from its parent, Python walks up and stops at the first match, and super() reaches the parent. Then polymorphism: one call, a different method for each object, with Animal, Employee and Shape examples and their real output.
Python Multiple Inheritance, the MRO and Mixins
A class can have two parents or a whole chain of them, and one list puts them in order: the MRO. Read it, watch Python walk it, see super() follow it, and build JsonMixin and LogMixin for a User class.
