Skip to Content
Lab 3

Object-Oriented Programming

Overview and Objectives

In this lab you will apply object-oriented programming (OOP) principles by:

  • Defining classes with attributes and methods to model real-world entities.
  • Implementing inheritance by extending a base class.
  • Handling exceptions within an OOP context.

By the end of this lab, you will be able to create classes (such as BankAccount and its subclass SavingsAccount), implement methods with error checking, and raise/catch exceptions appropriately.

Instructions and Tasks

Task 1: Defining a Base Class (BankAccount)

  1. Create a class BankAccount in a file (e.g., bank.py) that includes:

    • Attributes:
      • account_number
      • owner
      • balance
    • Initializer:
      • __init__(self, account_number, owner, balance=0) that sets the initial values.
    • Methods:
      • deposit(self, amount): Adds the given amount to balance. Allow only positive amounts; if a non-positive amount is passed, raise a ValueError with an appropriate message.
      • withdraw(self, amount): Subtracts the given amount from balance if sufficient funds exist. If the withdrawal amount is greater than the current balance, raise a ValueError (or your custom exception, if you choose to implement Task 3) indicating insufficient funds. Otherwise, deduct the amount and return the new balance.
      • __str__(self): Returns a string representation of the account (e.g., "Account 12345 – Owner: Alice, Balance: $500").
  2. Write test code (either within a main section in bank.py or in a separate test file) to:

    • Create an instance of BankAccount.
    • Demonstrate a successful deposit and withdrawal.
    • Attempt a withdrawal that exceeds the balance to trigger and catch the exception, printing an error message.

Task 2: Subclassing and Inheritance (SavingsAccount)

  1. In the same file or a new file (e.g., savings.py), create a subclass SavingsAccount that inherits from BankAccount:

    • Additional Attribute:
      • interest_rate (representing the annual interest rate as a percentage).
    • Initializer:
      • Modify the initializer to accept interest_rate along with other parameters and call the base class initializer using super().__init__().
    • Additional Method:
      • apply_interest(self): Calculate the interest based on the current balance and interest_rate, and add it to the balance. For example, if the interest rate is 5%, add balance * 0.05 to the balance.
    • Method Overriding:
      • Override the __str__ method to include the interest rate in the account’s string representation.
  2. Write test code that:

    • Creates an instance of SavingsAccount.
    • Demonstrates the inherited deposit and withdraw functionalities.
    • Calls apply_interest() and prints the account to verify that the balance updates correctly and the interest rate is displayed.

Task 3: Custom Exception Class (Optional Extension)

  1. (Optional) Define a custom exception class InsufficientFundsError in your module:
    • The class should inherit from Python’s built-in Exception class.
  2. Modify the withdraw method in BankAccount so that when a withdrawal amount exceeds the balance, it raises InsufficientFundsError (instead of ValueError).
  3. Update your test code to catch InsufficientFundsError specifically and print an appropriate error message (e.g., “Insufficient funds: cannot withdraw $X from account Y”).

Submission

Submit the following files via a link to a single GitHub repository containing all the files.:

  • bank.py (containing the BankAccount class and associated test code).
  • savings.py (or include the SavingsAccount class in bank.py if preferred) with test code.
  • If implemented, the custom exception class may be included in bank.py or as a separate file (e.g., exceptions.py).

Include example outputs (screenshots or text logs) showing:

  • Successful deposits and withdrawals.
  • The account string output before and after applying interest.
  • Proper handling of an attempted overdraw (with the error message).

Grading Rubric

CriteriaPointsDescription
BankAccount Class Implementation20 ptsThe BankAccount class is implemented with all required attributes and methods. Full credit if deposit and withdraw correctly update the balance, validate amounts, and raise exceptions for errors. Partial credit for minor omissions or errors.
Exception Handling in BankAccount10 ptsThe deposit and withdraw methods enforce rules (no negative deposits, no overdrafts) by raising exceptions with clear messages. Full credit if exceptions are raised and caught in test code; partial credit for one method missing proper validation.
SavingsAccount Subclass15 ptsThe SavingsAccount class inherits from BankAccount and adds the interest_rate attribute and apply_interest method. The overridden __str__ method includes the interest rate. Full credit if all functionalities work as specified; partial credit if any aspect is incomplete or erroneous.
Testing and Functionality Demonstration10 ptsTest code clearly demonstrates creation and usage of both BankAccount and SavingsAccount, including successful operations and proper exception handling. Partial credit if testing is incomplete or unclear.
Code Quality and Documentation5 ptsCode is well-organized, with meaningful variable and function names, and includes comments explaining key sections (such as the purpose of methods and exception handling).

Total Points: 60 points

Note

Partial credit will be awarded for submissions that demonstrate a correct understanding of OOP concepts and partial implementation of required tasks. For instance, if the BankAccount class is correctly defined but has minor issues with error checking, or if the SavingsAccount subclass is implemented but the overridden __str__ method is incomplete, evaluators may award points proportionate to the work correctly completed. Points may be deducted for missing methods, logical errors in deposit/withdrawal functionality, or insufficient exception handling. Credit will be given where the underlying approach is sound and the code clearly attempts to meet the rubric criteria, even if minor errors are present.