DEV Community

sanadiqbal
sanadiqbal

Posted on

OBJECT ORIENTED PROGRAMMING IN PYTHON

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

# using class keyword we make a class called MyClass
class MyClass:
     pass

Enter fullscreen mode Exit fullscreen mode

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.

class Student:
     full_name=str()
     roll=int()
     std=int()
     age=int()
Enter fullscreen mode Exit fullscreen mode

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.

Raj=Student()
Raj.full_name='Raj Kapoor'
Raj.roll=23
Raj.std=5
print(Raj.roll)
# Output : 23
Enter fullscreen mode Exit fullscreen mode

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.

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

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.

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

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:

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

Types of inheritance

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

Example :

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

2.Multiple inheritance : One child class derives properties

from more than one base class.

Example :

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

Enter fullscreen mode Exit fullscreen mode

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

Example :

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

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

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.

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

Method overriding : Method overriding allows specific implementation of a method in child class that is already present in parent class.

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

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.

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

Enter fullscreen mode Exit fullscreen mode

References

OOPs concepts - GeeksforGeeks
Abstract classes - GeeksforGeeks
Method overriding - GeeksforGeeks

Top comments (0)