Simplified: Object-oriented Programming Python
Tags: python, oop, beginners, computerscience
Published: 2021-08-15 19:42:00

![python o.o.p](https://cdn.fs.teachablecdn.com/ySDOMxZwTAio4hQ6k68G)
##Introduction
Before diving into O.O.P, I wish to pass a special appreciation  to <a href="">Lux Tech Academy</a> and more to its Founder <a href="https://dev.to/grayhat">Harun</a>, 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

<p>It is a great experience and Would encourage you to apply for the next cohort.</p>

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 
```python
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(<a href="https://dev.to/titusnjuguna/understanding-functions-in-python-40f8">To Understand more on functions </a>). For simplified definition,
Lets consider a dog,which according to scientific classification belongs to the species <a href="https://en.wikipedia.org/wiki/Dog">Canis lupus</a>, 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.

```python
class Dog:
   species = 'Canis lupus'
   def __init__(self,color,weight,height):
      self.color = color
      self.weight = weight
      self.height = height
```

```python
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

 ```python
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:
```python
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:
```python
Car1 = Car()
```
Go ahead and try creating an object out of Car2  as described above in [Google Colab](https://colab.research.google.com/drive/1r1S94i_Q0WdcdGVCXfIlgsEIW1YALfm1#scrollTo=c5HIOxO6hfgp)
**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
```python
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
```python
Car3 = Car('Blue','2018','Mazda')
Car3.hoot()
print(f'The {Car3.color},{Car3.YOM},{Car3.model} is hooting {Car3.hoot()}')
```
Result:
```python
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](https://dev.to/titusnjuguna/methods-in-python-o-o-p-20f8)

**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
```python
#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
```python
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)
```python 
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:
```python
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:
```python
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.
###Referee
- 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/