Simplified: Object-oriented Programming Python

titusnjuguna

Tito

Posted on August 15, 2021

Simplified: Object-oriented Programming Python

python o.o.p

Introduction

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

What is Object-oriented Programming?

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.

Principles of Object-Oriented Programming

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
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode
class Car:
    def __init__(self,color,YOM,model):
       self.color = color
       self.YOM = YOM
       self.model = model

Enter fullscreen mode Exit fullscreen mode

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}')
Enter fullscreen mode Exit fullscreen mode

Result:

This is a white,Toyota,manufactured in 2015
Enter fullscreen mode Exit fullscreen mode

In this example, Car1 is an object.Through it we can access all the attributes of class Car.Instantiating is basically:

Car1 = Car()
Enter fullscreen mode Exit fullscreen mode

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')
Enter fullscreen mode Exit fullscreen mode

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()}')
Enter fullscreen mode Exit fullscreen mode

Result:

The white,2016,Mazda is hooting Pipippipi
Enter fullscreen mode Exit fullscreen mode

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) 

Enter fullscreen mode Exit fullscreen mode

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

Enter fullscreen mode Exit fullscreen mode

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()
Enter fullscreen mode Exit fullscreen mode

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.
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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.

Referee

💖 💪 🙅 🚩
titusnjuguna
Tito

Posted on August 15, 2021

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related