For Enquiry: 93450 45466

Object Oriented Programming In Python



Object-oriented programming (OOP) is a programming concept based on the objects that interact with each other to perform the functions. Each object can be characterized by a behaviour and state. An object keeps the current state and the behavior in the fields and methods. It emphasizes the DRY(Don’t Repeat Yourself) Principle.

For instance, an object could represent an email with properties like subject, title, body and behaviors such as attachments, sending,organising.

OOP categorizes entities as software objects that have some data associated with them to perform operations upon.

Another common programming concept is Procedural Oriented Programming(POP), which structures a program like a food recipe which provides a finite number of steps, in the form of functions or code blocks, that flow sequentially in order to get the final result.

Major OOPs Concepts In Python

Classes

A class defines the attributes and behaviour of an object.For example if you have an Employee class, it can have attributes like name,salary and age, whereas its behaviour can include functions such as deduct or increment salary or calculate bonus etc.

Objects

Objects are the instances of classes or derived attributes and behaviours from class with actual data.

Methods

Functions under classes are known as methods.They define the behaviour of class.

Here is an example of classes and objects…

class Article:

    def __init__(self, title, content, author):

          self.title = title

          self.content = content

          self.author = author

    def represent(self):

          return f'{self.title,self.content,self.author}’

art_1 = Article(‘Automate the Boring Stuff’,

                      ‘Practical Programming..’,

                      ‘AL Sweigart’)

art_2= Article(‘Python Tricks’,

                     ‘A Buffet of Awesome Python..’,

                     ‘Dan Bader’)

print(art_1.represent())

 

Here the Article is a class and post_1 and post_2 are the objects or instances of the class.The __init__ function is a constructor that initialises or defines the attributes of the class.

Setting self.title=title or other attributes like this enables you to use the passed arguments using self.title in other parts of the class.

For instance if you change it to 

self.heading = title

Then you would use it as

def represent(self):

     return f'{self.heading,self.content,self.author}’

The output of the code is

(‘Automate the Boring Stuff’, ‘Practical Programming..’, ‘AL Sweigart’)

__str__ and __repr__ are the methods that will be invoked by default just like __init__ method to print the data of an instance when the object is called so you can avoid defining a custom represent method. These methods are also known as dunder or magic methods.

Checkout this Python Training Online by FITA. FITA provides a complete Python course where you will be building real-time projects like Bitly and Twitter bundled with Django, placement support and certification at an affordable price.

Inheritance

You might have some inheritance or resemblance of behaviours in you like your parents.Just like this, you can inherit properties of one class from another.The newly inherited class is a derived or child class and the former as base or Parent class.

Example Of Inheritance

class Post(Article):

     def __init__(self,title,content,author, image):

         super().__init__(title,content,author)

         self.image = image

def ret_image(self):

      try:

            img = Image.open(self.image)

            img.show()

            x = img.format

            y = img.mode

            return f’ Format: {x} Mode: {y}’

      except IOError:

           pass

post_1 = Post(‘Learn Python the Hard Way’,

                     ‘A Very Simple Intro..’, ‘AL Sweigart’, ‘book1.png’)

post_2 = Post(‘Python Tricks’,

                     ‘A Buffet of Awesome Python Features’, ‘Dan Bader’, ‘book2.png’)

print(post_2.ret_image())

Here we just needed to add another attribute and method and the rest of the attributes and methods are added to the child class by passing the Article argument to class name and defining super() method.

The output for the above program will include this and opens the image in the gallery

Format: PNG Mode:RGBA

The different types of inheritance are single-level, multi-level and hierarchical inheritance.

Polymorphism

Polymorphism is when you use a class method in different ways or in more than one way.There are two types of polymorphism

Run-time Polymorphism
Compile time Polymorphism

Here is an example of a program to have a better understanding of Polymorphism..

class FullTimeEmployee:

     def __init__(self, name, position, hours, salary):

          self.name = name

          self.position = position

          self.hours = hours

          self.salary = salary

    def bonus(self):

         return (self.salary * 0.5)


class PartTimeEmployee(FullTimeEmployee):

    def __init__(self, name, position, hours, salary):

         super().__init__(name, position, hours, salary)

   def bonus(self):

         return (self.salary * 0.1)

# common interface

def inc_bonus(object):

      x = object.bonus()

      print(f'{object.name}\’s bonus will be {x}’)

# instantiate objects

emp_1 = FullTimeEmployee(‘Atufa’, ‘Frontend Developer’, 6, 1000)

emp_2 = PartTimeEmployee(‘Shireen’, ‘Content Writer’, 8, 2000)

# passing the object

print(inc_bonus(emp_1))

print(inc_bonus(emp_2))

In the above code, the classes PartTimeEmployee and FullTimeEmployee are the Base and the derived classes respectively. A same method bonus works differently in both the classes, it returns a 50 percent bonus for a full time employee and a 10 percent bonus for a part time employee.

A common function inc_bonus calls the same bonus method of the class. The output for the above example

Atufa’s bonus will be 500.0

Shireen’s bonus will be 200.0

Encapsulation

Encapsulation in simple terms is to make the methods and attributes private or protected and give a level of security to be accessed outside the class.

In most of the other languages, the keywords public, private and protected are used to give a defined level of access outside the class, whereas in Python the _ (single underscore),__(double underscore) or no underscore is used before the attribute to define protected, private and public respectively. For instance,

class Post:

    def __init__(self, title, content, author, image):

        self.title = title

        self._content = content

        self.__author = author

        self.image = image

   def ret_image(self):

       img = Image.open(self.image)

       img.show()

emp_1 = Post(‘Automate The Boring Stuff’, ‘Practical Programming for..’, ‘atufa’,’default.jpg’)

print(emp_1.title)

print(emp_1.content)

print(emp_1.author)

You would get an AttributeError: ‘Post’ object has no attribute ‘content’.But when you can change it to this you can access it.

print(emp_1._content)

But now you will get the same error for other attribute

 AttributeError: ‘Post’ object has no attribute ‘__author’

But to access this you will need to define Getter method, and a Setter method to modify it.

Here’s how you would do it.

def show_author(self):

     print(self.__author)

def modify_author(self, new_author):

     self.__author = new_author

emp_1.show_author()

emp_1.modify_author(‘Shireen’)

The show_author is a custom getter method and modify_author is a custom setter method.

There are built-in decorators like @property and setter method in python to do this.

Data Abstraction

Abstraction is wherein the user is kept unaware of the code that is used for implementation, for instance, when you are buying a brand new phone, it is one thing for you, although there are many individual parts in this. Abstraction allows users to use the phone without knowing the complexity of the parts that form the phone.

This was all about Object Oriented Programming In Python. To get in-depth knowledge of Python along with its various applications and real-time projects, you can enroll in Python Training Institute in Chennai or Python Training in Bangalore by FITA at an affordable price, which includes certification, support and career guidance assistance.





  • Trending Courses

    JAVA Training In Chennai Software Testing Training In Chennai Selenium Training In Chennai Python Training in Chennai Data Science Course In Chennai Digital Marketing Course In Chennai DevOps Training In Chennai German Classes In Chennai Artificial Intelligence Course in Chennai AWS Training in Chennai UI UX Design course in Chennai Tally course in Chennai Full Stack Developer course in Chennai Salesforce Training in Chennai ReactJS Training in Chennai CCNA course in Chennai Ethical Hacking course in Chennai RPA Training In Chennai Cyber Security Course in Chennai IELTS Coaching in Chennai Graphic Design Courses in Chennai Spoken English Classes in Chennai Data Analytics Course in Chennai

    Spring Training in Chennai Struts Training in Chennai Web Designing Course In Chennai Android Training In Chennai AngularJS Training in Chennai Dot Net Training In Chennai C / C++ Training In Chennai Django Training in Chennai PHP Training In Chennai iOS Training In Chennai SEO Training In Chennai Oracle Training In Chennai Cloud Computing Training In Chennai Big Data Hadoop Training In Chennai UNIX Training In Chennai Core Java Training in Chennai Placement Training In Chennai Javascript Training in Chennai Hibernate Training in Chennai HTML5 Training in Chennai Photoshop Classes in Chennai Mobile Testing Training in Chennai QTP Training in Chennai LoadRunner Training in Chennai Drupal Training in Chennai Manual Testing Training in Chennai WordPress Training in Chennai SAS Training in Chennai Clinical SAS Training in Chennai Blue Prism Training in Chennai Machine Learning course in Chennai Microsoft Azure Training in Chennai Selenium with Python Training in Chennai UiPath Training in Chennai Microsoft Dynamics CRM Training in Chennai VMware Training in Chennai R Training in Chennai Automation Anywhere Training in Chennai GST Training in Chennai Spanish Classes in Chennai Japanese Classes in Chennai TOEFL Coaching in Chennai French Classes in Chennai Informatica Training in Chennai Informatica MDM Training in Chennai Big Data Analytics courses in Chennai Hadoop Admin Training in Chennai Blockchain Training in Chennai Ionic Training in Chennai IoT Training in Chennai Xamarin Training In Chennai Node JS Training In Chennai Content Writing Course in Chennai Advanced Excel Training In Chennai Corporate Training in Chennai Embedded Training In Chennai Linux Training In Chennai Oracle DBA Training In Chennai PEGA Training In Chennai Primavera Training In Chennai Tableau Training In Chennai Spark Training In Chennai Appium Training In Chennai Soft Skills Training In Chennai JMeter Training In Chennai Power BI Training In Chennai Social Media Marketing Courses In Chennai Talend Training in Chennai HR Courses in Chennai Google Cloud Training in Chennai SQL Training In Chennai CCNP Training in Chennai PMP Training in Chennai OET Coaching Centre in Chennai Business Analytics Course in Chennai NextJS Course in Chennai Vue JS Course in Chennai

  • Read More Read less
  • Are You Located in Any of these Areas

    Adambakkam, Adyar, Akkarai, Alandur, Alapakkam, Alwarpet, Alwarthirunagar, Ambattur, Ambattur Industrial Estate, Aminjikarai, Anakaputhur, Anna Nagar, Anna Salai, Arumbakkam, Ashok Nagar, Avadi, Ayanavaram, Besant Nagar, Bharathi Nagar, Camp Road, Cenotaph Road, Central, Chetpet, Chintadripet, Chitlapakkam, Chengalpattu, Choolaimedu, Chromepet, CIT Nagar, ECR, Eechankaranai, Egattur, Egmore, Ekkatuthangal, Gerugambakkam, Gopalapuram, Guduvanchery, Guindy, Injambakkam, Irumbuliyur, Iyyappanthangal, Jafferkhanpet, Jalladianpet, Kanathur, Kanchipuram, Kandhanchavadi, Kandigai, Karapakkam, Kasturbai Nagar, Kattankulathur, Kattupakkam, Kazhipattur, Keelkattalai, Kelambakkam, Kilpauk, KK Nagar, Kodambakkam, Kolapakkam, Kolathur, Kottivakkam, Kotturpuram, Kovalam, Kovilambakkam, Kovilanchery, Koyambedu, Kumananchavadi, Kundrathur, Little Mount, Madambakkam, Madhavaram, Madipakkam, Maduravoyal, Mahabalipuram, Mambakkam, Manapakkam, Mandaveli, Mangadu, Mannivakkam, Maraimalai Nagar, Medavakkam, Meenambakkam, Mogappair, Moolakadai, Moulivakkam, Mount Road, MRC Nagar, Mudichur, Mugalivakkam, Muttukadu, Mylapore, Nandambakkam, Nandanam, Nanganallur, Nanmangalam, Narayanapuram, Navalur, Neelankarai, Nesapakkam, Nolambur, Nungambakkam, OMR, Oragadam, Ottiyambakkam, Padappai, Padi, Padur, Palavakkam, Pallavan Salai, Pallavaram, Pallikaranai, Pammal, Parangimalai, Paruthipattu, Pazhavanthangal, Perambur, Perumbakkam, Perungudi, Polichalur, Pondy Bazaar, Ponmar, Poonamallee, Porur, Pudupakkam, Pudupet, Purasaiwakkam, Puzhuthivakkam, RA Puram, Rajakilpakkam, Ramapuram, Red Hills, Royapettah, Saidapet, Saidapet East, Saligramam, Sanatorium, Santhome, Santhosapuram, Selaiyur, Sembakkam, Semmanjeri, Shenoy Nagar, Sholinganallur, Singaperumal Koil, Siruseri, Sithalapakkam, Srinivasa Nagar, St Thomas Mount, T Nagar, Tambaram, Tambaram East, Taramani, Teynampet, Thalambur, Thirumangalam, Thirumazhisai, Thiruneermalai, Thiruvallur, Thiruvanmiyur, Thiruverkadu, Thiruvottiyur, Thoraipakkam, Thousand Light, Tidel Park, Tiruvallur, Triplicane, TTK Road, Ullagaram, Urapakkam, Uthandi, Vadapalani, Vadapalani East, Valasaravakkam, Vallalar Nagar, Valluvar Kottam, Vanagaram, Vandalur, Vasanta Nagar, Velachery, Vengaivasal, Vepery, Vettuvankeni, Vijaya Nagar, Villivakkam, Virugambakkam, West Mambalam, West Saidapet

    FITA Velachery or T Nagar or Thoraipakkam OMR or Anna Nagar or Tambaram or Porur or Pallikaranai branch is just few kilometre away from your location. If you need the best training in Chennai, driving a couple of extra kilometres is worth it!