Bank account class example in python

Python allows four different paradigms in coding. You can code using imperative, procedural, functional, or the object oriented approach in python. Object oriented programming is a popular programming paradigm. Let’s experiment with OOP paradigm by creating a simple bank account class. What are some typical functionality that a bank account may have?

a) The class declaration.
b) Data about the customer such as their first name, last name, account number, and balance.
c) The ability to make a deposit.
d) The ability to make a withdrawal.
e) The ability to see the most recent transaction.

a) Let’s code each of these segments step by step. But before we do that we need to get the simplest part out of the way which is creating the class. To create a class in python use the class keyword. Below is an example of it in action:

>>> class BankAccount:
...     """A class example in python that models a bank account"""
... 

The string with triple quotes is known as a docstring and is the string and describes what the class does.

b) Now that we got that out of the way we can move on to the second part which is to create the constructor. The method that you use for this is the __init__() method. You can view more of it by reading the python docs:

Here’s some of the details of the __init__() method:
• It works with the __new__() method. The __init__() method is called after the instance is created by the __new__() method.
• The __new__() method creates the object and the __init__() method customizes it.
• The method details are: object.__init__(self[, …])
◦ The arguments are those passed into the class constructor expression.

The funny syntax of having a leading and trailing double underscore is known as dunder methods which are short for double unders. These are special types of methods that adds functionality to classes. We can add these details under the __init__() constructor.

class BankAccount:
    """A class example in python that models a bank account"""
    def __init__(self, first_name, last_name, account_num, balance=0):
        self.first_name = first_name
        self.last_name = last_name
        self.account_num = account_num
        self.balance = balance
        self.transactions = []

As you can see we have the class declaration, a docstring that describes the class, and the __init__() method (constructor) which initializes the object. Underneath the __init__() method are several variables which are initialized. As again, this is what the constructor is for, it helps setup the state of the object. It will be difficult not to notice the self keyword that’s appended to the variables on the left hand side. Well, for clarification it’s actually not a keyword but a convention; in theory you could use another word as a substitute but pythonistas typically keep it as self for consistency. The self keyword is used to refer to the instance on which methods are bounded to. By using the self convention we set instance variables and not class ones.

c) This can be done by creating a simple method. A method is similar to a function except that it’s binded to a class. Below is the method that you can use for this purpose:

def deposit(self, amount):
    self.balance += amount
    return amount

The deposit() method takes the object variable and adds the amount that gets passed in to it.

d) The withdrawal method needs some extra consideration. The reason being is that you can’t make a withdrawal if the amount you’re trying to withdraw is greater than the balance you have in your account. Also, most banks set a cap on the amount of money that customers can withdraw within a day. Let’s assume that the limit for the bank account that we’re trying to simulate caps the daily withdrawal to $500. Here’s one solution to the problem:

def withdrawal(self, amount, limit=500):
        if self.balance - amount > 0 and amount <= limit:
            self.balance -= amount
            return amount
        else:
            return 'Your withdrawal amount is ${} which exceeds your account limit! You have:' \
                   '\n${}. Your withdrawal limit is {}'.format(amount, self.balance, limit)

e) This can be done by storing the deposits and withdrawals in a list, and treating it like a stack by popping elements. Since stacks are LIFO (Last in First Out data structures), the last item added to the stack will be popped out or the most recent transaction. We can do this by appending every successful deposit and withdrawal into the transactions list. Then, we can create a method that returns a popped item from the list. Here’s the updated deposit() and withdrawal() methods:

def deposit(self, amount):
    self.balance += amount
    self.transactions.append(+amount)
    return amount
def withdrawal(self, amount, limit=500):
    if self.balance - amount > 0 and amount <= limit:
        self.balance -= amount
        self.transactions.append(-amount)
        return amount
    else:
        return 'Your withdrawal amount is ${} which exceeds your account limit! You have:' \
               '\n${}. Your withdrawal limit is {}'.format(amount, self.balance, limit)

Here’s the newly added recent_transactions() method that returns the most recent transaction. Note, a condition that checks that the list has at least one element is included to prevent an exception from occurring if an item is popped from an empty list. Below is the method for that:

def recent_transactions(self):
    if len(self.transactions) < 1:
        return None
    else:
        return self.transactions.pop()

Below is the completed code for the BankAccount class with a couple of added simple methods that returns the values of some methods:


###############################################################
#
# A simple class to introduce object oriented
# programming in python. Models a bank account class.
# By Doug Purcell
# Owner of www.purcellconsult.com
#
#################################################################

class BankAccount:
    """A class example in python that models a bank account"""
    def __init__(self, first_name, last_name, account_num, balance=0):
        self.first_name = first_name
        self.last_name = last_name
        self.account_num = account_num
        self.balance = balance
        self.transactions = []
    def deposit(self, amount):
        self.balance += amount
        self.transactions.append(+amount)
        return amount
    def withdrawal(self, amount, limit=500):
        if self.balance - amount > 0 and amount <= limit:
            self.balance -= amount
            self.transactions.append(-amount)
            return amount
        else:
            return 'Your withdrawal amount is ${} which exceeds your account limit! You have:' \
                   '\n${}. Your withdrawal limit is {}'.format(amount, self.balance, limit)
    def get_first_name(self):
        return self.first_name
    def get_last_name(self):
        return self.last_name
    def get_account_num(self):
        return self.account_num
    def get_balance(self):
        return self.balance
    def recent_transactions(self):
        if len(self.transactions) < 1:
            return None
        else:
            return self.transactions.pop()
a = BankAccount('Doug', 'Purcell', 3628902828)
print('first name =', a.get_first_name())
print('last name =', a.get_last_name())
print('account number =', a.get_account_num())
print('account balance =', a.get_balance())
print('deposit =', a.deposit(20))
print('recent transaction is:', a.recent_transactions())
print('account balance =', a.get_balance())
print('withdrawal =', a.withdrawal(50))
print('recent transaction is =', a.recent_transactions())
print('account balance =', a.get_balance())
print('deposit =', a.deposit(500))
print('withdrawal =', a.withdrawal(891))
print('recent transaction is =', a.recent_transactions())
print('withdrawal =', a.withdrawal(49))
print('recent transaction is =', a.recent_transactions())
first name = Doug
last name = Purcell
account number = 3628902828
account balance = 0
deposit = 20
recent transaction is: 20
account balance = 20
withdrawal = Your withdrawal amount is $50 which exceeds your account limit! You have:
$20. Your withdrawal limit is 500
recent transaction is = None
account balance = 20
deposit = 500
withdrawal = Your withdrawal amount is $891 which exceeds your account limit! You have:
$520. Your withdrawal limit is 500
recent transaction is = 500
withdrawal = 49
recent transaction is = -49

Note, to use a method you must first create an instance of a class. Then, once the instance is created you can use that instance to call the method. If the class has an __init__() method like in this case, then when you call the method you must pass in the required arguments.

============================================================================ Want to learn how to use Python's most popular IDE Pycharm? In the free pdf guide "Getting the Hang of PyCharm" you'll learn all of the amazing features in PyCharm along with how to get started with data science. Subscribe to the Purcell Consult newsletter and get started A.S.A.P.