15
Simplified: Object-oriented Programming Python
Before diving into O.O.P, I wish to pass a special appreciation to Lux Tech Academy and more to its Founder Harun, for the opportunity to learn and network through a four-weeks Python 2021 Boot camp. The boot camp had weekly segments as follows:
- Week 1: Introduction to Python And Technical Writing
- Week 2: Advance Python concepts
- Week 3: Introduction to Web Development (Flask And FastAPI)
- Week 4: Introduction To Data Science
- Week 5 to Up-to-date: Peer Learning And Mentorship
It is a great experience and Would encourage you to apply for the next cohort.
In this article, I will give general definition,syntax and codes of each O.O.P principles . Intermediate and Real-life application of O.O.P will be covered in upcoming series
Just like the name suggests,Object-oriented programming is a technique in computer programming that represents data and methods as 'objects'. They ensure creation of neat and reusable code such that the program is divided into self-contained objects or several mini-programs.
The object has two characteristics:Attributes ,Behavior
Consider an example of a car
- Attributes of the car : color, year of manufacture, Manufacturer
- Behavior/Characteristics : Hoots, brakes, accelerates
In python , Object-oriented programming follows these principles: Class, Object, Method, Inheritance, Polymorphism, Data Abstraction, and Encapsulation.
1. Class
A Class is like an object constructor, or a "blueprint" for
creating objects,by defining the common attributes and
behavior.
In Python, a class is defined using a keyword 'class'. Lets define a car
class Car:
#class attributes
Color="Red"
YOM = "2015"
Model = "Mazda"
pass
Congratulations for defining a class,but you will realize the end goal of any program is a result.Unfortunately , the class defined will run smoothly but will give no result. We will handle this in objects
The example above is a class in a simplest form, and is not really useful in real life applications. In real-life application , a class needs to be dynamic.
Therefore, I will introduce 'init()' function,which is always executed when the class is being initiated(To Understand more on functions ). For simplified definition,
Lets consider a dog,which according to scientific classification belongs to the species Canis lupus, now as you go down the scientific classification you will realize subspecies have different attributes e.g color,weight,height etal
With these information lets define a class dog.
class Dog:
species = 'Canis lupus'
def __init__(self,color,weight,height):
self.color = color
self.weight = weight
self.height = height
class Car:
def __init__(self,color,YOM,model):
self.color = color
self.YOM = YOM
self.model = model
Just like the car definition, the code will run but there is no end result.
To solve this, allow me to introduce instantiation in the next concept of O.O.P,objects.
2.Object
To access the attributes of a class, we need to create an instance(event) out of the class.Out of this we can simply define an object as an instance of a class.
Considering the car example, take the following instance:
** Car1 ; color:white,YOM:2015,model:Toyota
** Car2 ; color:blue,YOM:2012, model:Audi
class Car:
def __init__(self,color,YOM,model):
self.color = color
self.YOM = YOM
self.model = model
Car1 = Car('white','2015','Toyota')
print ( f'This is a {Car1.color},{Car1.model},manufactured in {Car1.YOM}')
Result:
This is a white,Toyota,manufactured in 2015
In this example, Car1 is an object.Through it we can access all the attributes of class Car.Instantiating is basically:
Car1 = Car()
Go ahead and try creating an object out of Car2 as described above in Google Colab
3.Method
Recall on definition of a class, we mentioned that an object has two properties: an attribute and behavior. Now in a simpler term, a method is a way of defining behavior of an object.
From the Car example, we can say a car has the following behaviors: it hoots,it accelerates, it brakes etal
Therefore lets create a method out of it
class Car:
def __init__(self,color,YOM,model):
self.color = color
self.YOM = YOM
self.model = model
#method
def hoot(self):
return('Pipippipi')
To access the method , we will have to create an instance
Car3 = Car('Blue','2018','Mazda')
Car3.hoot()
print(f'The {Car3.color},{Car3.YOM},{Car3.model} is hooting {Car3.hoot()}')
Result:
The white,2016,Mazda is hooting Pipippipi
Addition
Methods can be classified into 3:
- Instance Method
- Class Method
- Static Method
I will go deeper into this methods and their applications in my next post.Kindly keep in touch.Check here
4.Inheritance
Think of inheritance in the following terms, parent class and a child class.In real-life scenario, a child can partially or fully inherit some attributes and behaviors from their parents.
Now programming scenario,Inheritance allows us to define a child class that inherits all the methods and properties from parent class.
NOTE: A child class can inherit some methods and properties by using Parent_class_name.init() function . Additionally, it can inherit all the methods and properties from parent class Use the super().init() Function. We will handle both in the following examples respectively.
Example 1: Partial inheritance
#Parent Class
class Person:
def __init__(self, fname, lname):
self.firstname = fname
self.lastname = lname
#method
def printname(self):
print(self.firstname, self.lastname)
#child class
class Student(Person):
def __init__(self, fname, lname):
Person.__init__(self, fname, lname)
Example 2 : Full inheritance
class Person:
def __init__(self, fname, lname):
self.firstname = fname
self.lastname = lname
#method
def printname(self):
print(self.firstname, self.lastname)
class Student(Person):
def __init__(self, fname, lname):
super().__init__(fname, lname)
self.graduationyear = 2019
5.Polymorphism
Imagine, you have been tasked to create a program that calculate area of any shape provided by user.Now this is the perfect situation to introduce polymorphism, which simply means different form.
In the programming world, Polymorphism refers to the ability of the function with the same name to carry different functionality altogether. It creates a structure that can use many forms of objects.
Example(Polymorphism with Class Methods)
class whale:
def swim(self):
print("The whale is swimming.")
def swim_backwards(self):
print("The whale cannot swim backwards, but can sink backwards.")
def skeleton(self):
print("The whale's skeleton is made of cartilage.")
class Starfish():
def swim(self):
print("The Starfish is swimming.")
def swim_backwards(self):
print("The Starfish can swim backwards.")
def skeleton(self):
print("The Starfish's skeleton is made of bone.")
waza = whale()
herod = Starfish()
for fish in (waza, herod):
fish.swim()
fish.swim_backwards()
fish.skeleton()
Output:
The whale is swimming.
The whale cannot swim backwards, but can sink backwards.
The whale's skeleton is made of cartilage.
The Starfish is swimming.
The Starfish can swim backwards.
The Starfish's skeleton is made of bone.
6.Data Abstraction
For easy understanding, consider your T.V remote, the '+' button,which is used to increase the volume.You can use the button but you cannot see how operations are carried out. This is a perfect example of abstraction.
In Python, data abstraction can be defined as ,hiding all the irrelevant data/process of an application in order to reduce complexity and increase the efficiency of the program.
If you have worked with Django Framework, consider when creating a model:
from django import models
class student(models.Model)
pass
This a perfect example of abstraction.
In future posting i will further discuss Abstract Methods and Classes.Keep in touch
7.Encapsulation
Encapsulation is an Object Oriented Programming concept that binds together the data and functions that manipulate the data, and that keeps both safe from outside interference and misuse. Data encapsulation led to the important OOP concept of data hiding.
- https://www.pythontutorial.net/python-oop/
- https://www.analyticsvidhya.com/blog/2020/11/basic-concepts-object-oriented-programming-types-methods-python/
- https://www.w3schools.com/python/python_inheritance.asp -http://rubyblog.pro/2017/01/object-oriented-programming-encapsulation-inheritance
- https://www.askpython.com/python/oops/polymorphism-in-python
- https://www.mygreatlearning.com/blog/abstraction-in-python/
15