Learn Python Classes by Building a Banking System
A step-by-step guide to learning Python OOP through a simple banking system project.
Hello, fellow coders! My name is CyCoderX, and today, I’m excited to help you dive into the world of classes in Python. Understanding classes is fundamental to mastering object-oriented programming (OOP), and what better way to learn than by building a simple project together?
Keep in mind that I also have an additional article titled “Python Classes and Objects: An Essential Introduction,” where you can learn the theory and key concepts of OOP.
Remember, there’s no better practice than hands-on experience! I always encourage readers to improve upon what I show them and demonstrate the concepts they’ve learned, or even try tackling the problem themselves. This approach not only reinforces your understanding but also helps you gain valuable experience that can be applied in real-world scenarios.
And don’t forget, CONSISTENCY is key; regularly practicing and applying what you’ve learned ensures that the knowledge becomes second nature.
In this article, we’ll create a basic banking system, which will illustrate the key concepts of classes, objects, attributes, and methods. By the end of this tutorial, you will have a solid grasp of how to implement and use classes in Python.
Why Learn About Classes?
Classes are the blueprint for creating objects in Python. They allow us to encapsulate data and functionality together, making our code more modular, reusable, and easier to maintain. This is particularly useful in large projects where organization and structure are crucial.
Project Overview: Basic Banking System
Our project will involve creating a basic banking system with the following components:
- Bank Account Class: This class will represent a bank account and will include attributes like account number, account holder’s name, and balance. It will also contain methods for depositing and withdrawing money, as well as checking the balance.
- Transaction History: We’ll implement a way to keep track of all transactions made to and from the account.
- User Interaction: Finally, we’ll create a simple interface for users to interact with our banking system, allowing them to perform operations like creating an account, making deposits and withdrawals, and viewing their transaction history.
What Will You Learn?
By the end of this article, you will have learned:
- How to define a class in Python and create objects from it.
- The importance of attributes and methods in a class.
- How to use constructors to initialize objects.
- How to implement basic functionality like deposits, withdrawals, and balance checks.
- The benefits of encapsulation and how to use it to create more robust and maintainable code.
Let’s Get Started!
We’ll start with the basics of defining a class and gradually build up our banking system step by step. Follow along, and by the end, you’ll have a practical understanding of how classes work in Python.
Interested in more Python content? Don’t worry I got you covered! Feel free to explore some of my lists on medium!
Defining the Bank Account Class
To begin our project, we’ll start by defining the BankAccount class. This class will serve as the blueprint for creating bank account objects. Each account will have attributes like account number, account holder's name, and balance. We'll also include methods for depositing and withdrawing money, as well as checking the balance.
Step 1: Define the Class and Its Attributes
Let’s create our BankAccount class with the necessary attributes.
class BankAccount:
def __init__(self, account_number, account_holder, initial_balance=0):
self.account_number = account_number
self.account_holder = account_holder
self.balance = initial_balance
self.transactions = []
def __str__(self):
return f"Account[{self.account_number}] - Holder: {self.account_holder} - Balance: ${self.balance}"__init__ method: This is the constructor method in Python. It initializes the object's attributes when a new instance of the class is created.
account_number: The unique identifier for the bank account.account_holder: The name of the account holder.initial_balance: The starting balance of the account, defaulting to 0.transactions: A list to store the history of transactions for the account.
__str__ method: This special method returns a string representation of the object, making it easier to print and inspect.
Step 2: Add Methods for Deposits, Withdrawals, and Balance Check
Now, we’ll add methods to perform basic operations on the account: deposit, withdraw, and check balance.
class BankAccount:
def __init__(self, account_number, account_holder, initial_balance=0):
self.account_number = account_number
self.account_holder = account_holder
self.balance = initial_balance
self.transactions = []
def __str__(self):
return f"Account[{self.account_number}] - Holder: {self.account_holder} - Balance: ${self.balance}"
def deposit(self, amount):
if amount > 0:
self.balance += amount
self.transactions.append(f"Deposited: ${amount}")
print(f"${amount} deposited successfully.")
else:
print("Deposit amount must be positive.")
def withdraw(self, amount):
if amount > 0:
if amount <= self.balance:
self.balance -= amount
self.transactions.append(f"Withdrew: ${amount}")
print(f"${amount} withdrawn successfully.")
else:
print("Insufficient funds.")
else:
print("Withdrawal amount must be positive.")
def check_balance(self):
print(f"Current balance: ${self.balance}")
return self.balancedepositmethod: Adds a specified amount to the account balance and records the transaction.withdrawmethod: Subtracts a specified amount from the account balance, provided there are sufficient funds, and records the transaction.check_balancemethod: Prints and returns the current balance of the account.
Step 3: Add Method for Viewing Transaction History
To keep track of all transactions, we’ll add a method to view the transaction history.
class BankAccount:
def __init__(self, account_number, account_holder, initial_balance=0):
self.account_number = account_number
self.account_holder = account_holder
self.balance = initial_balance
self.transactions = []
def __str__(self):
return f"Account[{self.account_number}] - Holder: {self.account_holder} - Balance: ${self.balance}"
def deposit(self, amount):
if amount > 0:
self.balance += amount
self.transactions.append(f"Deposited: ${amount}")
print(f"${amount} deposited successfully.")
else:
print("Deposit amount must be positive.")
def withdraw(self, amount):
if amount > 0:
if amount <= self.balance:
self.balance -= amount
self.transactions.append(f"Withdrew: ${amount}")
print(f"${amount} withdrawn successfully.")
else:
print("Insufficient funds.")
else:
print("Withdrawal amount must be positive.")
def check_balance(self):
print(f"Current balance: ${self.balance}")
return self.balance
def view_transactions(self):
print("Transaction History:")
for transaction in self.transactions:
print(transaction)view_transactions method: Prints all recorded transactions, allowing the account holder to review their transaction history.
Putting It All Together
Here’s the complete BankAccount class with all the methods integrated:
class BankAccount:
def __init__(self, account_number, account_holder, initial_balance=0):
self.account_number = account_number
self.account_holder = account_holder
self.balance = initial_balance
self.transactions = []
def __str__(self):
return f"Account[{self.account_number}] - Holder: {self.account_holder} - Balance: ${self.balance}"
def deposit(self, amount):
if amount > 0:
self.balance += amount
self.transactions.append(f"Deposited: ${amount}")
print(f"${amount} deposited successfully.")
else:
print("Deposit amount must be positive.")
def withdraw(self, amount):
if amount > 0:
if amount <= self.balance:
self.balance -= amount
self.transactions.append(f"Withdrew: ${amount}")
print(f"${amount} withdrawn successfully.")
else:
print("Insufficient funds.")
else:
print("Withdrawal amount must be positive.")
def check_balance(self):
print(f"Current balance: ${self.balance}")
return self.balance
def view_transactions(self):
print("Transaction History:")
for transaction in self.transactions:
print(transaction)This comprehensive class definition covers the essential operations of our basic banking system. Next, we’ll create a simple user interaction interface to demonstrate how to use this class.
Creating a User Interaction Interface
To make our banking system more interactive, we’ll create a simple interface that allows users to perform operations like creating an account, making deposits and withdrawals, and viewing their transaction history. This will involve writing a script that interacts with our BankAccount class. Additionally, we are going to make it more modular, which will offer several benefits.
Get CyCoderX’s stories in your inbox
Join Medium for free to get updates from this writer.
By adopting a modular approach into our application, we can enhance maintainability, as each module can be developed, tested, and debugged independently, making it easier to manage and update the system. It will also improve scalability, allowing new features and functionalities to be added without affecting the existing system, thus enabling seamless expansion. Furthermore, modularity increases reusability, as modules can be reused across different parts of the application or even in other projects, saving development time and effort. Lastly, it facilitates collaboration, as different team members can work on separate modules simultaneously, improving productivity and reducing development time.
Step 1: Import the BankAccount Class
First, ensure that you import the BankAccount class from the file where it’s defined. We can name it bank_account.py, and then we would import it as follows:
from bank_account import BankAccountStep 2: Define the User Interaction Functions
We’ll define several functions to handle different user actions.
def create_account():
account_number = input("Enter account number: ")
account_holder = input("Enter account holder's name: ")
initial_balance = float(input("Enter initial balance: "))
return BankAccount(account_number, account_holder, initial_balance)
def perform_deposit(account):
amount = float(input("Enter amount to deposit: "))
account.deposit(amount)
def perform_withdrawal(account):
amount = float(input("Enter amount to withdraw: "))
account.withdraw(amount)
def check_balance(account):
account.check_balance()
def view_transactions(account):
account.view_transactions()create_account: Prompts the user to enter account details and returns a newBankAccountobject.perform_deposit: Prompts the user to enter a deposit amount and calls thedepositmethod on the account.perform_withdrawal: Prompts the user to enter a withdrawal amount and calls thewithdrawmethod on the account.check_balance: Calls thecheck_balancemethod to display the current balance.view_transactions: Calls theview_transactionsmethod to display the transaction history.
Step 3: Create the Main Menu
We’ll create a main menu to allow users to choose different actions.
def main():
print("Welcome to the Basic Banking System")
account = create_account()
print("Account created successfully!\n")
while True:
print("\nMenu:")
print("1. Deposit")
print("2. Withdraw")
print("3. Check Balance")
print("4. View Transactions")
print("5. Exit")
choice = input("Enter your choice: ")
if choice == '1':
perform_deposit(account)
elif choice == '2':
perform_withdrawal(account)
elif choice == '3':
check_balance(account)
elif choice == '4':
view_transactions(account)
elif choice == '5':
print("Exiting the system. Goodbye!")
break
else:
print("Invalid choice. Please try again.")main function: This function displays the main menu, processes user input, and calls the appropriate functions based on the user's choice.
Complete User Interaction Script
Here is the complete script combining all the parts:
from bank_account import BankAccount
def create_account():
account_number = input("Enter account number: ")
account_holder = input("Enter account holder's name: ")
initial_balance = float(input("Enter initial balance: "))
return BankAccount(account_number, account_holder, initial_balance)
def perform_deposit(account):
amount = float(input("Enter amount to deposit: "))
account.deposit(amount)
def perform_withdrawal(account):
amount = float(input("Enter amount to withdraw: "))
account.withdraw(amount)
def check_balance(account):
account.check_balance()
def view_transactions(account):
account.view_transactions()
def main():
print("Welcome to the Basic Banking System")
account = create_account()
print("Account created successfully!\n")
while True:
print("\nMenu:")
print("1. Deposit")
print("2. Withdraw")
print("3. Check Balance")
print("4. View Transactions")
print("5. Exit")
choice = input("Enter your choice: ")
if choice == '1':
perform_deposit(account)
elif choice == '2':
perform_withdrawal(account)
elif choice == '3':
check_balance(account)
elif choice == '4':
view_transactions(account)
elif choice == '5':
print("Exiting the system. Goodbye!")
break
else:
print("Invalid choice. Please try again.")
if __name__ == "__main__":
main()This script provides a user-friendly interface for interacting with the BankAccount class, allowing users to manage their bank accounts through simple commands.
Conclusion and Additional Resources
Nice job and thank you for taking the time to read through my article! Together we have successfully created a basic banking system in Python, illustrating the fundamental concepts of classes, objects, attributes, and methods. Through this project, you’ve learned how to:
- Define a class in Python and create objects from it.
- Use constructors to initialize objects.
- Implement methods for basic functionality like deposits, withdrawals, and balance checks.
- Maintain and view a transaction history.
- Create a simple user interaction interface.
Understanding and using classes is a crucial step in mastering object-oriented programming (OOP). This knowledge not only makes your code more organized and modular but also prepares you for more advanced programming concepts and projects.
Final Thoughts
By building a simple banking system, you’ve gained practical experience with classes and object-oriented programming in Python. This foundational knowledge will serve you well as you tackle more complex projects and continue your journey as a Python developer.
Remember, practice is key to mastering programming concepts. Keep experimenting with different projects and challenges to strengthen your understanding. You can even try to build on top of this script by adding new features such as:
- Implementing account types like savings and checking accounts.
- Adding more sophisticated transaction types, such as transferring funds between accounts.
- Enhancing security with password protection and encryption.
- Integrating with a database to persist data between sessions.
The possibilities are endless, and each new challenge will help solidify your grasp of object-oriented programming. Keep coding and exploring, and you’ll continue to grow as a developer. Happy coding!
Final Words:
Thank you for taking the time to read my article.
This article was first published on medium by CyCoderX.
Hey There! I’m CyCoderX, a data engineer who loves crafting end-to-end solutions. I write articles about Python, SQL, AI, Data Engineering, lifestyle and more!
Join me as we explore the exciting world of tech, data and beyond!
For similar articles and updates, feel free to explore my Medium profile.
If you enjoyed this article, consider following for future updates.
Interested in Python content and tips? Click here to check out my list on Medium.
Interested in more SQL, Databases and Data Engineering content? Click here to find out more!
What did you think about this article? Let me know in the comments below … or above, depending on your device 🙃
In Plain English 🚀
Thank you for being a part of the In Plain English community! Before you go:
- Be sure to clap and follow the writer ️👏️️
- Follow us: X | LinkedIn | YouTube | Discord | Newsletter
- Visit our other platforms: CoFeed | Differ
- More content at PlainEnglish.io









