• Chennai, Bangalore & Online: 93450 45466Coimbatore: 95978 88270Madurai: 97900 94102

  • 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.






    Quick Enquiry

    Please wait while submission in progress...


    Contact Us

    Chennai

      93450 45466

    Bangalore

     93450 45466

    Coimbatore

     95978 88270

    For Hiring

     93840 47472
     hr@fita.in

    Corporate Training

     90036 23340


    FITA Academy Branches

    Chennai
    Bangalore
    Coimbatore
    Other Locations
    FITA Academy - Velachery
    Plot No 7, 2nd floor,
    Vadivelan Nagar,
    Velachery Main Road,
    Velachery, Chennai - 600042
    Tamil Nadu

        :   93450 45466

    FITA Academy - Anna Nagar
    No 14, Block No, 338, 2nd Ave,
    Anna Nagar,
    Chennai 600 040, Tamil Nadu
    Next to Santhosh Super Market

        :   93450 45466

    FITA Academy - T Nagar
    05, 5th Floor, Challa Mall,
    T Nagar,
    Chennai 600 017, Tamil Nadu
    Opposite to Pondy Bazaar Globus

        :   93450 45466

    FITA Academy - Tambaram
    Nehru Nagar, Kadaperi,
    GST Road, West Tambaram,
    Chennai 600 045, Tamil Nadu
    Opposite to Saravana Jewellers Near MEPZ

        :   93450 45466

    FITA Academy - Thoraipakkam
    5/350, Old Mahabalipuram Road,
    Okkiyam Thoraipakkam,
    Chennai 600 097, Tamil Nadu
    Next to Cognizant Thoraipakkam Office and Opposite to Nilgris Supermarket

        :   93450 45466

    FITA Academy - Porur
    17, Trunk Rd,
    Porur
    Chennai 600116, Tamil Nadu
    Above Maharashtra Bank

        :   93450 45466

    FITA Academy Marathahalli
    No 7, J J Complex,
    ITPB Road, Aswath Nagar,
    Marathahalli Post,
    Bengaluru 560037

        :   93450 45466

    FITA Academy - Saravanampatty
    First Floor, Promenade Tower,
    171/2A, Sathy Road, Saravanampatty,
    Coimbatore - 641035
    Tamil Nadu

        :   95978 88270

    FITA Academy - Singanallur
    348/1, Kamaraj Road,
    Varadharajapuram, Singanallur,
    Coimbatore - 641015
    Tamil Nadu

        :   95978 88270

    FITA Academy - Madurai
    No.2A, Sivanandha salai,
    Arapalayam Cross Road,
    Ponnagaram Colony,
    Madurai - 625016, Tamil Nadu

        :   97900 94102

    FITA Academy - Pondicherry
    410, Villianur Main Rd,
    Sithananda Nagar, Nellitope,
    Puducherry - 605005
    Near IG Square

        :   93635 21112

  • Trending Courses

    JAVA Training In Chennai Dot Net Training In Chennai Software Testing Training In Chennai Cloud Computing Training In Chennai AngularJS Training in Chennai Big Data Hadoop Training In Chennai Android Training In Chennai iOS Training In Chennai Web Designing Course In Chennai PHP Training In Chennai Digital Marketing Course In Chennai SEO Training In Chennai

    Oracle Training In Chennai Selenium Training In Chennai Data Science Course In Chennai RPA Training In Chennai DevOps Training In Chennai C / C++ Training In Chennai UNIX Training In Chennai Placement Training In Chennai German Classes In Chennai Python Training in Chennai Artificial Intelligence Course in Chennai AWS Training in Chennai Core Java Training in Chennai Javascript Training in ChennaiHibernate Training in ChennaiHTML5 Training in ChennaiPhotoshop Classes in ChennaiMobile Testing Training in ChennaiQTP Training in ChennaiLoadRunner Training in ChennaiDrupal Training in ChennaiManual Testing Training in ChennaiSpring Training in ChennaiStruts Training in ChennaiWordPress Training in ChennaiSAS Training in ChennaiClinical SAS Training in ChennaiBlue Prism Training in ChennaiMachine Learning course in ChennaiMicrosoft Azure Training in ChennaiUiPath Training in ChennaiMicrosoft Dynamics CRM Training in ChennaiUI UX Design course in ChennaiSalesforce Training in ChennaiVMware Training in ChennaiR Training in ChennaiAutomation Anywhere Training in ChennaiTally course in ChennaiReactJS Training in ChennaiCCNA course in ChennaiEthical Hacking course in ChennaiGST Training in ChennaiIELTS Coaching in ChennaiSpoken English Classes in ChennaiSpanish Classes in ChennaiJapanese Classes in ChennaiTOEFL Coaching in ChennaiFrench Classes in ChennaiInformatica Training in ChennaiInformatica MDM Training in ChennaiBig Data Analytics courses in ChennaiHadoop Admin Training in ChennaiBlockchain Training in ChennaiIonic Training in ChennaiIoT Training in ChennaiXamarin Training In ChennaiNode JS Training In ChennaiContent Writing Course in ChennaiAdvanced Excel Training In ChennaiCorporate Training in ChennaiEmbedded Training In ChennaiLinux Training In ChennaiOracle DBA Training In ChennaiPEGA Training In ChennaiPrimavera Training In ChennaiTableau Training In ChennaiSpark Training In ChennaiGraphic Design Courses in ChennaiAppium Training In ChennaiSoft Skills Training In ChennaiJMeter Training In ChennaiPower BI Training In ChennaiSocial Media Marketing Courses In ChennaiTalend Training in ChennaiHR Courses in ChennaiGoogle Cloud Training in ChennaiSQL Training In Chennai CCNP Training in Chennai PMP Training in Chennai OET Coaching Centre in Chennai

  • Are You Located in Any of these Areas

    Adyar, Adambakkam, Anna Salai, Ambattur, Ashok Nagar, Aminjikarai, Anna Nagar, Besant Nagar, Chromepet, Choolaimedu, Guindy, Egmore, K.K. Nagar, Kodambakkam, Koyambedu, Ekkattuthangal, Kilpauk, Meenambakkam, Medavakkam, Nandanam, Nungambakkam, Madipakkam, Teynampet, Nanganallur, Navalur, Mylapore, Pallavaram, Purasaiwakkam, OMR, Porur, Pallikaranai, Poonamallee, Perambur, Saidapet, Siruseri, St.Thomas Mount, Perungudi, T.Nagar, Sholinganallur, Triplicane, Thoraipakkam, Tambaram, Vadapalani, Valasaravakkam, Villivakkam, Thiruvanmiyur, West Mambalam, Velachery and Virugambakkam.

    FITA Velachery or T Nagar or Thoraipakkam OMR or Anna Nagar or Tambaram or Porur 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!