OBJECT ORIENTED PROGRAMMING IN PYTHON
Tags: python
Published: 2023-02-16 06:38:16

## OBJECT ORIENTED PROGRAMMING



Object Oriented Programming (OOPs) is a programming paradigm where object and classes are used for programming. By Object oriented programming real world entities like inheritance are implemented in programming. The main concept of OOPs is to bind the data and the functions that work together as a single unit so that no other part of the code can access this data.



## MAIN CONCEPTS OF OBJECT ORIENTED PROGRAMMING

* Class
* Object
* Polymorphism
* Encapsulation
* Inheritance
* Data Abstraction

## CLASS

Class is a collection of objects.It is the blueprint from which objects are created.Class is made up of attributes and methods.Attributes are the variables in the class and methods  are the functions inside the class. Making a class does not consume any memory. So basically classes are created to organise data into logical units.

**Creating a class in python**
```python
# using class keyword we make a class called MyClass
class MyClass:
     pass

```
## OBJECT 

Object is an instance of a class.We can think of it as a variable made using the datatype class.Classes are made specifically to create objects.Classes contains all the attributes and methods that it's object will have.
For example if we make a class called student and create attributes for this class.
```python 
class Student:
     full_name=str()
     roll=int()
     std=int()
     age=int()
```
We make an object of this class in our main program.We can access the attributes of the class which are public using the dot operator.Attributes are public.
```python
Raj=Student()
Raj.full_name='Raj Kapoor'
Raj.roll=23
Raj.std=5
print(Raj.roll)
# Output : 23
```
**init method:**
init method is basically made to initialise the attributes while the objects are being made.If  we don't make an init function the compiler makes one for us by default and it takes no argument.While making the object we initialise it by passing values to it's attributes.The first argument in init while defining it is self.self keyword is used to access the attributes in the class.


```python
class Student():
    def __init__(self,first,last,age_):
        self.first_name=first
        self.last_name=last
        self.age=age_


Raj=Student('Raj','Kapoor',25)

print(Raj.first_name)
# Output : Raj
```
**Creating methods in class**
A method in OOPs is a procedure or a function within a class.
Method of an object can only access the attributes of that object.The first argument while defining a method is always self.

```python
class Student():
    def __init__(self,first,last,age_):
        self.first_name=first
        self.last_name=last
        self.age=age_
    def set_email(self):
        email=self.first_name+'.'+self.last_name+'@email.com'
        return email

Raj=Student('Raj','Kapoor',25)

print(Raj.set_email())

#Output : Raj.Kapoor@email.com
```

## INHERITANCE

Inheritance is the capability of one class to inherit properties from another class.The class which inherits the properties is called child class or derived class and the class from which the properties are inherited is called parent class or base class.
The advantages of inheritance in OOPs are :
* It represents real world relationship.
* Improves the reusability of code.
* It's transitive by nature.If a class Q inherits the properties of class P and class R inherits the properties of class Q,then class R automatically inherits the property of class P.
*Enhances code readabilty.
 
Example of inheritance:

```python
class Student():
    def __init__(self,first,last,age_):
        self.first_name=first
        self.last_name=last
        self.age=age_
    def email(self):
        email=self.first_name+'.'+self.last_name+'@email.com'
        return email
class CollegeStudent(Student):
    def __init__(self,first,last,age_,college):
        self.first_name=first
        self.last_name=last
        self.age=age_
        self.college=college


Rahul=CollegeStudent('Rahul','Kapoor',25,'IIT')

print(Rahul.email())

# Output : Rahul.Kapoor@email.com
```
**Types of inheritance**

1.Single inheritance : When the child is derived from only on single base class it's called single inheritance.

Example :
```python
class Animal():
    name=str()
    sound=str()

class Dog(Animal):
    def set_sound(self):
        self.sound='woof'



tommy=Dog()
tommy.set_sound()
print(tommy.sound)
# Output : woof
```
2.Multiple inheritance : One child class derives properties   
from more than one base class.

Example :
```python
class Dad:
    def sing():
        print('Good singer')

class Mom:
    def art():
        print('Good artist')

class Son(Dad,Mom):
    pass

Gon=Son()
Son.sing()
Son.art()
 # Output : Good singer
            Good artist

```
3.Hierarchical inheritance : Multiple child class inherits properties from a single class.

Example :

```python
class Animal():
    name=str()
    sound=str()

class Dog(Animal):
    def set_sound(self):
        self.sound='woof'

class Cat(Animal):
    def set_sound(self):
        self.sound='meow'

tommy=Dog()
snowball=Cat()
snowball.set_sound()
tommy.set_sound()
print(tommy.sound)
print(snowball.sound)
```

4. Multilevel inheritance : When a class derives properties from a parent  class which itself is a derived class.The class made inherits the properties of it's parent class as well as the parent class of it's parent class. 

Example :
```python
class Grandpa : 
    def height(self):
        print('Good height')

class Dad(Grandpa):
    def hair(self):
        print('Good hair')

class Son(Dad):
    def player(self):
        print('Good player')


goku=Son()
print(goku.player())
print(goku.height())
print(goku.hair())

# Output :Good player
#         None
#         Good height
#         None
#         Good hair
#         None
```
## POLYMORPHISM

Polymorphism simply means taking many forms.It enables same method to have different functionalities according to the class it is in.Same method can perform different function in the parent and the derived class as well as in different classes. Polymorphism is implemented in OOPs by duck typing,method overriding and method overloading.
Duck typing : Duck typing means that the type of the object is of concern only during the runtime and we don't need to mention the type of the object before performing any operation on it.Python supports dynamic duck typing.

```python
class Car():
    def sound(self):
        return 'zoom'
class Dog():
    def sound(self):
        return 'woof'

tommy=Dog()
print(tommy.sound())
tesla=Car()
print(tesla.sound())

#Output : woof
#         zoom
```
Method overriding : Method overriding allows specific implementation of a method in child class that is already present in parent class.

```python
class Car():
    def sound(self):
        return 'zoom'
class SportsCar(Car):
    def sound(self):
        return 'vrooom'

tesla=SportsCar()
print(tesla.sound())
maruti=Car()
print(maruti.sound())
```

## ENCAPSULATION 

Encapsulation is the grouping of data and methods that work on the data within a single unit.This puts restriction on accessing the data and methods directly to prevent accidently changing the data. The attributes are made private for this purpose. A class is an encapsulation as it encapsulates all the attributes and methods related to a single thing.

## ABSTRACTION

Abstraction is the process of hiding unnecessary complex data from the user that the user has no need of and also hiding sensitive information from the user.
Abstraction is implemented in python by creating abstract class.

```python
from abc import ABC,abstractclassmethod

class Shape(ABC):
    @abstractclassmethod
    def sides(self):
        pass

class Triangle(Shape):
    def sides(self):
        return 3
    
class Square(Shape):
    def sides(self):
        return 4
    
abc=Triangle()
print(abc.sides())
pqrs=Square()
print(pqrs.sides())

# Output : 3
#          4

```
## References
[OOPs concepts - GeeksforGeeks](https://www.geeksforgeeks.org/python-oops-concepts/)
[Abstract classes - GeeksforGeeks](https://www.geeksforgeeks.org/abstract-classes-in-python/)
[Method overriding - GeeksforGeeks]
(https://www.geeksforgeeks.org/method-overriding-in-python/)