Single logo
  • Courses
  • Blog
  • About
Join on SkoolJoin on Skool

In this topic

Python
  • Python for AI: The Five Tools You Actually Need
  • Thinking Like a Python Architect in an AI-First World
  • Your First Python Program: print, Comments, sep and end
  • Set Up PyCharm for Python: Install, First Project and First Run
  • Run a Python File and Read the Error: Tracebacks in Three Steps
  • Python Data Types, Variables and Strings: Indexing, Slicing and f-strings
  • Python Operators: Arithmetic, Comparison, Logical, Membership, Identity and Precedence
  • Python Conditionals and Loops: if/elif/else, for, while, break and continue
  • Looping Over Real Data in Python: Dicts, Lists of Dicts, enumerate and zip
  • Checking AI-Written Python Code: A Six-Step Habit That Finds Three Hidden Faults
  • Python Basics Practice: Report Card, Shopping Cart and Password Checker from a Prompt
  • Python Functions: Parameters, Return, Scope (LEGB), *args and **kwargs
  • Type Hints on Python Functions: Parameters, Returns, None and Collections
  • Python lambda, map, filter, Modules and Packages (with pip and venv)
  • Python Functions Practice: Bonus Calculator, Product Pipeline and a Math Package
  • Python Lists, Tuples, Sets and Dicts, Plus Type Hints on Variables
  • Python Comprehensions: List, Dict, Set and Generator Expressions, Read as Loops
  • Python Class Methods, Static Methods and Properties: What Each One Receives
  • Python Classes and Objects: __init__, self and PEP 8 Names
  • Python Inheritance and Polymorphism: super(), Overriding and Duck Typing
  • Python Multiple Inheritance, the MRO and Mixins
  • Python Encapsulation and Special Methods: Underscores, __str__, __add__ and __len__
  • Python Composition, Abstract Classes and Dataclasses
  • Python OOP Practice: Design a Bank, an Employee System and a Library
  • Set Up a Python AI Project with uv, VS Code and an API Key in .env
  • uv and pyproject.toml: Start, Add, Run and Rebuild a Python Project
  • Python try and except Basics: Catch an Error and Keep Going
  • Read and Write a File in Python: open, with, Modes and Encoding
  • Python Custom Exceptions and Advanced Error Handling: raise, raise from and the Call Stack
  • Python Logging and Debugging: Levels, Handlers, logger.exception and breakpoint()
  • Python File Modes, pathlib and Context Managers: x, r+, rb, Path and __enter__/__exit__
  • Python CSV, JSON and Large Files: csv, json, yield Pipelines, tomllib and pickle
  • Python Practice: Build a Log File Analyzer and a File Organizer
  • Python Project Structure for AI-Assisted Development: Packages, config.py and AGENTS.md
  • Regular Expressions in Python: search, findall, Groups and Greedy vs Lazy
  • Testing Python Code with pytest: assert, parametrize, fixtures and pytest.raises
  • Async Python: async def, await, asyncio.gather and the Blocking Trap
  • Django, FastAPI or Flask? The Same Blog Feature in Three Shapes, and How to Choose
  • One Blog, Three Frameworks: Routing, Models, Templates and Layout in Django, FastAPI and Flask
  • Getting Started with Flask: Routes, Jinja2 Templates and WSGI in One Small App
  • Your First Flask App with uv: From an Empty Folder to a Page in Debug Mode
  • Flask Routes, Templates and url_for: Converters, Forms, Redirects and the Signed Session
  • Flask-SQLAlchemy Models and Flask-Migrate: From a Python Class to a Real Table
  • Building a Blog with an AI Coding Agent: Plan Mode, a Master Prompt and the First Review
  • Handing a Figma Design to an AI Agent: Compare the Files, Then Review the Change
  • Inside a Flask Blog: The App Factory, Blueprints, the Instance Folder and CORS Done Right
  • How a Request and a Login Flow Through a Flask Blog: Flask-Login, CSRF and the Signed Session
  • Testing a Flask Blog with pytest: A Test App from the Factory, Fixtures and the Test Client
  1. Blog
  2. /
  3. Python
  4. /
  5. Object-Oriented Python

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.

Chaand Sheikh

·27 November 2026·Updated 28 November 2026Object-Oriented Python

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."

  1. The nouns become classes: Bank, Account, Transaction.
  2. The verbs become methods: deposit, withdraw, transfer.
  3. What describes each thing becomes attributes: owner, balance.
  4. The relationships pick the tool: is a means inheritance, has a means composition.
  5. 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.

Class diagram of the banking system: Bank has many Accounts; abstract Account has SavingsAccount and CheckingAccount as children; Account has many Transaction dataclasses Bank _accounts Account (ABC) balance: read-only Transaction @dataclass has many has many SavingsAccount add_interest() CheckingAccount overdraft=200 is a
The five questions, drawn as a class diagram before any code is written.

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.

Tried the exercise? Share your answer or ask a question.

The StudyEasy AI Community is free to join, with the lesson files, notebooks and code.

Join free on Skool

Keep going in Python · 24 of 48

Previous
Python Composition, Abstract Classes and Dataclasses
Next post
Set Up a Python AI Project with uv, VS Code and an API Key in .env

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.

On this page

  • Design first: five questions
  • Use case 1: an online banking system
  • Read it against what you asked for
  • Use case 2: an employee management system
  • Use case 3: a library management system
  • Four more to practise
  • A cheat sheet for every design
  • Try it yourself
Community · Free to join
Single logo

StudyEasy AI Community

Hosted onSkool

Learn AI engineering, share what you build, and connect with other learners.

  • Free resources: lesson files, notebooks and code

  • Ask questions and join engineering discussions

  • Meet real people learning and building with AI

Join free on Skool

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)

Single logo

Empowering Education, One Course at a Time

About
About usContact us
Legal
Terms of UsePrivacy Policy

© 2026 StudyEasy Organization. All rights reserved.