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)
-
Create a class
BankAccountin a file (e.g.,bank.py) that includes:- Attributes:
account_numberownerbalance
- Initializer:
__init__(self, account_number, owner, balance=0)that sets the initial values.
- Methods:
deposit(self, amount): Adds the given amount tobalance. Allow only positive amounts; if a non-positive amount is passed, raise aValueErrorwith an appropriate message.withdraw(self, amount): Subtracts the given amount frombalanceif sufficient funds exist. If the withdrawal amount is greater than the current balance, raise aValueError(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").
- Attributes:
-
Write test code (either within a
mainsection inbank.pyor 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.
- Create an instance of
Task 2: Subclassing and Inheritance (SavingsAccount)
-
In the same file or a new file (e.g.,
savings.py), create a subclassSavingsAccountthat inherits fromBankAccount:- Additional Attribute:
interest_rate(representing the annual interest rate as a percentage).
- Initializer:
- Modify the initializer to accept
interest_ratealong with other parameters and call the base class initializer usingsuper().__init__().
- Modify the initializer to accept
- Additional Method:
apply_interest(self): Calculate the interest based on the current balance andinterest_rate, and add it to the balance. For example, if the interest rate is 5%, addbalance * 0.05to the balance.
- Method Overriding:
- Override the
__str__method to include the interest rate in the account’s string representation.
- Override the
- Additional Attribute:
-
Write test code that:
- Creates an instance of
SavingsAccount. - Demonstrates the inherited
depositandwithdrawfunctionalities. - Calls
apply_interest()and prints the account to verify that the balance updates correctly and the interest rate is displayed.
- Creates an instance of
Task 3: Custom Exception Class (Optional Extension)
- (Optional) Define a custom exception class
InsufficientFundsErrorin your module:- The class should inherit from Python’s built-in
Exceptionclass.
- The class should inherit from Python’s built-in
- Modify the
withdrawmethod inBankAccountso that when a withdrawal amount exceeds the balance, it raisesInsufficientFundsError(instead ofValueError). - Update your test code to catch
InsufficientFundsErrorspecifically 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 theBankAccountclass and associated test code).savings.py(or include theSavingsAccountclass inbank.pyif preferred) with test code.- If implemented, the custom exception class may be included in
bank.pyor 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
| Criteria | Points | Description |
|---|---|---|
| BankAccount Class Implementation | 20 pts | The 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 BankAccount | 10 pts | The 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 Subclass | 15 pts | The 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 Demonstration | 10 pts | Test 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 Documentation | 5 pts | Code 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
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.