Introduction
Object Oriented Programming ( OOP ) is a programming paradigm. This programming perspective aids us to model real world things into code and solve complex problems. A good majority of general purpose programming languages make use of it. Interestingly, Python is built via the OOP way.
The following are required fundamental knowledge prerequisites:
- Primitive data types
- Mathematical and boolean operators
- Variables
- Arrays
- Functions
- While and For loops
You can download the raw source code here
Classes
OOP helps us resemble physical things into code. Which in turn means, we are making a new data type or classifying something. Take for example two dogs, Balto and Brody. Both share common characteristics and behaviours of any general dog. That is, Balto and Brody are both instances of class Dog.
Below is a simple blueprint for the concept Dog
# declare a new class
class Dog:
''' Defining a Dog '''
# characteristics
def __init__(self,name,age,color):
self.dog_name = name
self.dog_age = age
self.dog_color = color
#behaviours
def bark(self):
''' Make dog bark'''
return "woof, woof"
def sit(self):
''' Make dog sit'''
return f"{self.dog_name}" is now sitting."
In python __init__() is basically a constructor for instances (Balto and Brody) of classes. When we create a new dog, we call the constructor and pass it a name, age and color. These variables in classes are known as attributes. The keyword self is a reference to the instance or object that is created.
We also define behaviours or methods for classes. We narrow down what is most common for any dog to have; that it can bark and sit.
Objects
Objects are instances of Classes. They are unique in state, but share commonality in attributes and methods, which are inherited by their blueprint or class.
Continuing with the Dog class, below is how you would go about creating an object and using it:
#creating an object of Dog
dog_01 = Dog('balto',4,'brown')
#finding out dog_01 name
print(dog_01.name)
#using inherited methods
print(dog_01.bark())
Above, we instantiated a dog object programmatically. We gave it attributes and accessed dog_01 name. Additionally, we told the dog to 'bark'.
The following output would be this:
>>> balto
>>> woof,woof
Application
As you get better with classes and objects you can begin to simulate real world situations into code. For example take a banking system. You have the ability to open up a bank; deposit and withdraw money and, check your balances and your profile. Let us put these into action:
class Bank():
'''A Simple Banking System'''
def __init__(self,
fname,
account_num,
deposit=0):
self.user_name = fname.title()
self.account_number = account_num
# implicit attributes
self.balance = deposit
self.email = 'N/A'
self.telephone ='N/A'
#methods
def check_balance(self):
'''check user's balance'''
return self.balance
def deposit(self,amount):
'''deposit x amount'''
self.balance += amount
return self.balance
def withdraw(self,amount):
'''withdraw some money'''
if self.balance - amount < 0:
print(f'Insufficent Funds')
else:
print(f'You withdrew {self.balance} from {self.account_number}')
def profile_info(self):
return f'''
Account Number: {self.account_number}
=======================
Name: {self.user_name}
Primary Telephone: {self.telephone}
Email: {self.email} \n'''
A couple of things to note. You can have implicit attributes, making sure that that every instance instantiated is given a default value of some sort. Secondly, for security implications, it is important to have methods that modify the attributes in the background. Abstracting away unneccesary details for the user.
Always make sure to test your code:
user_01 = Bank('ali',1,0)
print(user_01.user_name)
# Depositing money
# before
print(user_01.check_balance())
user_01.deposit(100)
# after
print(user_01.check_balance())
#withdrawing too much
user_01.withdraw(20000)
# before
print(user_01.profile_info())
user_01.telephone = '999-999-999'
# after
print(user_01.profile_info())
The following should be the output:
>>>
Ali
0
100
Insufficent Funds
Account Number: 1
=======================
Name: Ali
Primary Telephone: N/A
Email: N/A
Account Number: 1
=======================
Name: Ali
Primary Telephone: 999-999-999
Email: N/A
Inheritance
Classes can also have subclasses. In otherwords, the parent class can have child classes which inherit its attributes and methods, while the children can have their own as well.
For example, continuing from our simple banking system we can create subclasses: chequing and savings. Both of which need the ability that the parent class Bank has, while remaining separate in functionality.
Consider the following subclass Chequing:
class Chequing(Bank):
""" A simple chequing account"""
# initialize parent/super class attr & meth with given child class attr & meth
def __init__(self,
fname,account_num,
chequing_account_number,deposit=0):
#pass instance args to parent constructor
super().__init__(fname,
account_num,
deposit)
# attributes unique to the child class Chequing
self.cheq_acc_num = chequing_account_number
self.service_monthly_charge = 'basic'
self.transaction_number_limit = 6
# child class methods
# overriding an inherited method
def check_balance(self):
if self.service_monthly_charge == 'basic':
if self.balance < 2000:
self.balance -= 5.99
return self.balance
else:
return self.balance
A few of things to note. The child class must explicitly state what parent class its inheriting from at the outset. Secondly, when we create a chequing object, its attributes must be passed to the parent class constructor using super()- a reference to the parent class. And finally, we can override inherited methods via the same name and defining new rules.
We test our code:
#instantiate an object
user_01 = Chequing('ali',1,100001,1000)
#test
user_01.check_balance()
print(user_01.balance)
Output should be:
>>>
994.01
Conclusion
Object Oriented Programming is an important programming paradigm because it aids programmers to solve complex problems. Your code is abstracted, clean and secure. All of which are important principles to programming in general.
I hope this technical documentation has helped you into becoming a better programmer. I encourage you to play with the code or better yet, improve it. See if you can make a savings account.
Reference
All documentation from this page uses the concepts learned in: Python Crash Course by Eric Matthes
You can also learn more about python via these links: