• Teaching
    • Montessori Teacher Training 🔥
    • Yoga Teacher Training
  • Coding
    • Full Stack Development Course
    • Data Science Course
    • Python Programming Course
    • Software Testing Course
    • Architecting on AWS
  • Commerce
    • PwC Edge : Strategic Accounting and Finance Programme
    • ACCA Course
    • SAP Fico Course
    • Practical Accounting Course
    • SAP MM Course
    • HR Management Course in Kerala
  • Technical
    • Structural Design Course
    • Embedded Systems Software Engineering in Kerala
    • MEP Course
    • MEP QS Course
    • BIM Training Course
    • Quantity Survey Course
  • Finacademy
    • Forex Trading Course
    • Stock Market Course
    • Mutual Funds Course in Kerala
  • Digital Marketing
    • Digital Marketing Course
    • Performance Marketing Course
  • Language Learning
    • Spoken English Course
    • German Language Course
    • IELTS Exam Coaching
  • Exam Preparation
    • Kerala PSC Coaching
    • Kerala PSC LGS Coaching
    • KAS Coaching
    • Kerala PSC LDC Coaching
    • Kerala PSC LSGS Coaching
    • KPSC Industries Extension Officer Coaching
    • KPSC Technical Mechanical Coaching
    • KPSC Technical Electrical Coaching
    • Kerala PSC Technical Exam Preparation
    • KPSC Technical Civil Coaching
    • SBI PO Coaching
    • IBPS Clerk Coaching
    • IBPS PO Coaching
    • IBPS SO Coaching
    • Bank Exam Coaching
    • Lecturer in DIET Course
    • Kpsc HSA Coaching
    • KPSC LP UP Assistant Coaching
    • EMRS Coaching
    • KTET Coaching
    • SSC Coaching
    • SSC JE Coaching
    • SSC CGL Coaching
    • SSC CHSL Coaching
    • SSC MTS Coaching
    • UPSC Coaching
  • Health Care
    • DHA Course
    • OET Coaching
  • Other Exams
    • GATE Coaching
    • CAT Coaching
    • MAT Online Coaching
    • KMAT Online Coaching
Entri Blog
No Result
View All Result
Saturday, May 17, 2025
  • Kerala PSC
    • Kerala PSC General
      • Kerala PSC Exams
      • KAS Exam
      • Kerala PSC VEO Notification
      • Kerala Police SI
      • Kerala PSC LDC Notification
      • Kerala PSC Village Field Assistant Notification
      • Kerala PSC LD Typist Notification
      • Kerala PSC Food Safety Officer
      • Kerala PSC Excise Inspector Notification
      • Kerala PSC BDO Notification
      • Kerala PSC CPO Notification
      • Kerala PSC LGS Notification
      • Fire and Rescue Officer
      • Women Fire and Rescue Officer
    • Kerala PSC Teaching
      • Kerala PSC HSA
      • Kerala PSC HSST
      • KTET
      • LP/UP Assistant
      • KVS
      • Railway Teacher
    • Kerala PSC Technical
      • LSGD AE
      • Draftsman/Overseer
      • IEO
      • ATP
      • Polytechnic Lecturer
      • AE Electronics
      • Assistant Engineer
  • Banking
    • IBPS PO Notification
    • IBPS Clerk Notification
    • SBI PO Notification
    • SBI Clerk Notification
    • SBI SO Notification
    • SBI Apprentice Notification
    • Canara Bank PO Notification
    • Indian Bank PO Notification
    • RBI Assistant Notification
    • RBI Office Attendant Notification
    • IBPS RRB Notification
    • IBPS RRB Office Assistant Notification
  • Skilling
    • Coding
    • Spoken English
    • Stock Market
      • Share Market Today News
      • Share Market Analysis
    • Digital Marketing
    • Accounting Course
    • SAP
    • OET
    • German
    • IELTS
    • Quantity Survey
    • MEP
    • Structural Design
    • Montessori
    • Yoga Teaching
    • Oil and Gas
  • Courses
    • Data Science Course
      • Data Science Malayalam
      • Data Science Course in Tamil
      • Data Science Course in Telugu
      • Data Science Training in Kochi
      • Data Science Training in Trivandrum
      • Data Science Course in Calicut
      • Data Science Training in Thrissur
    • Data Analytics Course
      • Data Analytics Course in Malayalam
      • Data Analytics Course in Tamil
      • Data Analytics Course in Telugu
    • Technical Upskilling
      • Quantity Surveying Course
      • Structural Design Course
      • BIM Course in Kerala
      • MEP Course
      • Embedded System Course
      • MEP Quantity Surveying Course
      • MEP Course in Kochi
      • Quantity Surveyor Course in Tamil
      • Quantity Surveying Course in Telugu
      • Quantity Surveyor Course in Hyderabad
      • Quantity Surveying Course in Chennai
      • MEP Design Course in Kerala
      • HVAC Course
      • Steel Structure Design Course
      • RCC Design Course
    • Full Stack Developer Course
      • Full Stack Development Malayalam
      • Full Stack Development Hindi
      • Full Stack Development Tamil
      • Full Stack Development Telugu
      • Full Stack Development Kannada
    • Stock Market Course
      • Stock Market Course in Malayalam
      • Stock Market Course in Tamil
      • Stock Market Course in Kannada
      • Options Trading Course
    • Mutual Funds Course
    • Forex Trading Course
    • Spoken English Course
      • Spoken English Course in Malayalam
      • Spoken English Course in Hindi
      • Spoken English Course in Telugu
      • Spoken English Course in Tamil
      • Spoken English Course in Kannada
    • Python Programming Course
    • Software Testing Course
      • Software Testing Course in Malayalam
      • Software Testing Course in Tamil
      • Software Testing Course in Telugu
    • AWS Solutions Architect Associate Course
    • PwC Edge : Strategic Accounting and Finance Programme
    • Practical Accounting Course
      • Accounting Course in Malayalam
      • Accounting Course in Tamil
      • Tally Course
      • Taxation Course
      • UAE Accounting
      • GST Course
      • Zoho Books Training
      • GST Practitioner Course in Kerala
      • GCC VAT Course
    • ACCA Training Online
      • ACCA Course in Kerala
    • SAP Training Courses
      • SAP FICO Course
      • SAP MM Course
      • SAP SD Training
      • SAP FICO Course in Tamil
      • SAP MM Course in Tamil
    • HR Management Course
    • Performance Marketing Course
    • Mern Stack Developer Course
      • Full Stack Developer Course in Kochi
      • Full Stack Developer Course in Trivandrum
      • Full Stack Developer Course in Calicut
      • Full Stack Developer Course in Pune
      • Full Stack Developer Course in Bangalore
      • Full Stack Developer Course in Hyderabad
      • Full Stack Developer Course in Chennai
      • Full Stack Developer Course in Indore
      • Full Stack Developer Course in Jaipur
      • Full Stack Developer Course in Coimbatore
    • Digital Marketing Training
      • Digital Marketing Course in Kochi
      • Digital Marketing Course in Trivandrum
      • Digital Marketing Course in Calicut
      • Digital Marketing Course in Kollam
      • Digital Marketing Course in Thrissur
      • Digital Marketing Course in Kottayam
      • Digital Marketing Course in Kannur
    • Montessori Teacher Training
      • Montessori Teacher Training in Calicut
      • Montessori Teacher Training in Kochi, Ernakulam
      • Montessori Teacher Training in Trivandrum
      • Montessori Teacher Training in Kollam
      • Montessori Teacher Training in Malayalam
      • Montessori Teacher Training in Kannada
    • Other Courses
      • German Language Course
      • OET Coaching
        • OET for Pharmacist
        • OET for Nurses
      • DHA Course
      • MOH Exam Coaching
      • Nurses Recruitment Abroad
      • FMGE Coaching
      • ChatGPT Course
      • Forex Trading Course
      • Yoga Teacher Training Course
      • Diploma in Early Childhood Care and Education
      • Business Administration & Hospital Management Course
      • Hospital and Healthcare Administration
      • AI for Teachers Course
  • Others
    • Railway
      • RRB Technician Notification
      • RRB JE Notification
      • RRB ALP Notification
      • RRB NTPC Notification
      • RRB RPF Notification
      • RRB RPF SI Notification
      • RRB RPF Constable Notification
      • RRB Group D Notification
      • RRB RPSF SI Notification
      • RRB SSE Notification
    • SSC
      • SSC CPO Notification
      • SSC MTS Notification
      • SSC CGL Notification
      • SSC CHSL Notification
      • SSC GD Constable Notification
      • SSC Stenographer Notification
      • SSC JE Notification
      • SSC CAPF Notification
      • SSC JHT Notification
      • Delhi Police Constable Notification
      • Delhi Police SI Notification
    • GATE
    • MAT
    • KMAT
      • KMAT Kerala 2024
    • TET
      • APTET
      • CTET
      • DSSSB
      • Karnataka TET
      • Kerala TET
        • KTET Notification
      • KVS
      • MPTET
      • SUPER TET
      • TNTET
      • TSTET
      • UPTET
    • UPSC
      • UPSC CAPF Notification
      • UPSC CDS Notification
      • UPSC NDA Notification
      • UPSC Civil service Notification
  • Free Learn
    • Free Courses
      • Free Coding Courses
        • C Langauge Courses
        • Free Data Science Courses
        • Free Full Stack Developer Courses
        • Free Python Programming Courses
      • Free Accounting Courses
      • Free Digital Marketing Courses
        • Free SEO Courses
        • Web Development for Marketers
      • Engineering Upskilling Courses
      • Free Hospital Administration Courses
      • Free OET Training
      • Free SAP Courses
      • Free Teachers Training Courses
      • Free Trading Courses
        • Free Stock Market Courses in Malayalam
        • Free Options Trading Course Malayalam
        • Free Forex Trading Courses Malayalam
        • Free Personal Finance Courses Malayalam
    • Question Answer
    • Aptitude Questions
    • Webinars
  • Test Prep
    • Kerala PSC Coaching
      • KPSC Degree Level Exam Preparation
      • Kerala PSC 12th Level Exam Preparation
      • Kerala PSC 10th Level Exam Preparation
      • KAS Coaching
      • Kerala PSC LDC Coaching
      • Kerala PSC LD Typist Coaching
      • Kerala PSC Fireman Coaching
      • KSFE Assistant Exam Preparation
      • Secretariat Office Attendant Coaching
      • Secretariat Assistant Coaching
      • Kerala PSC SI Exam Coaching
      • Khadi Board LDC Exam Preparation
      • Devaswom Board LDC Coaching
      • University LGS Exam Preparation
      • University Assistant Exam Coaching
      • KPSC Scientific Officer Exam Coaching
      • KPSC Probation Officer Grade II
      • KPSC Food Safety Officer Coaching
      • KWA Sanitary Chemist Coaching
      • KPSC Diary Farm Instructor Exam Coaching
      • Kerala PSC KWA Lab Assistant Exam Coaching
      • Kerala PSC ICDS Supervisor Exam Coaching
      • KPSC Finger Print Searcher Coaching
      • Kerala PSC Welfare Officer Gr. II Exam Coaching
      • KPSC Assistant Dental Surgeon Coaching
    • KPSC Teaching Exams
      • HSA Exam Preparation
      • KPSC HSA Social Science Coaching
      • KPSC HSA Physical Science Coaching
      • KPSC HSA English Coaching
      • KPSC Junior Language Teacher Hindi
      • KTET Coaching
      • SET Coaching
      • LP/UP Assistant Exam Coaching
      • HSST Exam Preparation
      • HSST Commerce Exam Coaching
      • Kerala PSC Lecturer in Diet Coaching
      • KVS PGT/TGT Coaching
    • Kerala PSC Technical Exams Coaching
      • Assistant Engineer Electrical Exam Coaching
      • Assistant Engineer Electronics Coaching
      • Assistant Engineer Mechanical Coaching
      • Kerala PSC Industries Extension Officer Coaching
      • KPSC LSGD AE Exam Coaching
      • KPSC Civil Engineering Exam Coaching
      • KPSC Mechanical Engineering Exam Coaching
      • KPSC Electrical Engineering Exam Coaching
      • KPSC Electronics Engineering Exam Coaching
      • KPSC Technical Computer Science Coaching
      • KPSC Tradesman Turning Coaching
      • Kerala PSC Overseer Exam Coaching
      • KPSC Assistant Town Planner Coaching
      • Lecturer in Polytechnic Electronics Coaching
    • Teaching Exams Coaching
      • CSIR NET Exam Coaching
      • EMRS Coaching
      • CTET Exam Online Coaching
    • IELTS Training Online
    • Bank Exam Coaching Online
      • SEBI Grade A Coaching
      • IBPS SO Online Coaching
      • IBPSC PO Online Coaching
      • IBPSC Clerk Online Coaching
      • SBI PO Coaching
      • SBI Clerk Online Coaching
      • SBI Apprentice Class
      • SBI SO Online Coaching
      • RBI Grade B Coaching
      • RBI Assistant Coaching
      • CSEB Exam Coaching
      • IBPS RRB Coaching
      • IBPS RRB PO Coaching
      • Canara Bank Po Exam Coaching
      • Kerala Gramin Bank Coaching
      • Kerala Bank Exam Coaching
        • Kerala Bank Clerk Exam Coaching
        • Kerala Bank Office Attendant Exam Coaching
        • Kerala Bank Assistant Manager Exam Coaching
      • JCI Exam Coaching
      • NABARD Grade A Coaching
      • LIC AAO Coaching Online
    • UPSC Online Coaching
      • UPSC CAPF Online Coaching
    • SSC Online Coaching
      • SSC JE Online Coaching
      • SSC CGL Coaching
      • SSC CGL AAO Coaching
      • SSC CGL CBI Inspector Coaching
      • SSC CHSL Coaching
      • SSC MTS Coaching
      • SSC Stenographer Coaching
      • SSC GD Online Coaching
    • RRB Exams Coaching
      • RRB RPF Exam Coaching
      • RRB NTPC Exam Coaching
      • RRB JE Online Coaching
      • RRB JE Electronics Coaching
      • RRB ALP Exam Coaching
      • RRB Technician Exam Coaching
    • CAT Online Coaching
    • CMAT Online Coaching
    • XAT Exam Coaching
    • GATE Online Coaching
      • GATE CE Online Coaching
      • GATE ME Online Coaching
      • GATE EE Online Coaching
    • NMAT Exam Coaching
    • AAI ATC Jr Executive Coaching
    • Cochin Shipyard Executive Trainee Coaching
    • BEL Probationary Engineer Coaching
    • HPCL Junior Executive Coaching
Free Courses
Entri Blog
  • HTML Tutorial
  • DSA Tutorials
  • Tutorials in Hindi
    • HTML Tutorial for Beginners in Hindi
    • Python Tutorial for Beginners in Hindi
    • GIT and GITHUB Tutorial for Beginners in Hindi
  • Tutorials in Tamil
    • JavaScript Tutorial in Tamil
  • Tutorials in Telugu
    • HTML Tutorial For Beginners in Telugu
    • CSS Tutorial for Beginners in Telugu
    • Bootstrap Tutorial for Beginner in Telugu
  • Tutorials in Kannada
    • HTML Tutorial For Beginners in Kannada
entri exclusive offers entri exclusive offers
Home Articles

Object Oriented Programming Python: An Overview

by Feeba Mahin
April 28, 2023
in Articles, Python Programming
Object Oriented Programming Python An Overview
Share on FacebookShare on WhatsAppShare on Telegram

Table of Contents

  • Encapsulation in Python
  • What is Encapsulation?
  • What is Encapsulation in Python?
  • Methods to Control Access
  • Using Single Underscore
  • Using Double Underscores
  • Using Getter and Setter methods to access private variables
  • Benefits of Encapsulation in Python
  • What is the need for Encapsulation in Python
  • Main Concepts of Object-Oriented Programming (OOPs)
  • Class
  • Objects
  • Example 1: Creating a class and object with class and instance attributes
  • Inheritance
  • Polymorphism
  • Encapsulation
  • Data Abstraction 
  • Conclusion

Python is a multi-paradigm programming language. It supports different programming approaches.

One of the popular approaches to solve a programming problem is by creating objects. This is known as Object-Oriented Programming (OOP).

An object has two characteristics:

  • attributes
  • behavior

The concept of OOP in Python focuses on creating reusable code.

In Python, object-oriented Programming (OOPs) is a programming paradigm that uses objects and classes in programming. It aims to implement real-world entities like inheritance, polymorphisms, encapsulation, etc. in the programming. The main concept of OOPs is to bind the data and the functions that work on that together as a single unit so that no other part of the code can access this data.

Python and Machine Learning Square

Encapsulation in Python

When working with an Object Oriented Programming language like Python, encapsulation in Python is one of the 4 important concepts to understand. The other three are inheritance, polymorphism, and abstraction.

What is Encapsulation?

1: Which of the following data types is immutable in Python?

2: What does the len() function do in Python?

3: Which keyword is used to define a function in Python?

4: What will print(type([1, 2, 3])) output?

5: Which statement is correct about Python indentation?

    Fill out the form to see the results

    Ever wondered how much you really know? It's time to put your brain to the test!

    When working with classes and dealing with sensitive data, providing global access to all the variables used within the program is not a good choice. Encapsulation offers a way for us to access the required variables without providing the program full-fledged access to any of those variables.

    Updating, modifying, or deleting data from variables can be done through the use of methods that are defined specifically for the purpose. The benefit of using this approach to programming is improved control over the input data and better security.

    “Ready to take your python skills to the next level? Sign up for a free demo today!”

    🚀 Start Coding Today! Enroll Now with Easy EMI Options. 💳✨

    Gain expertise in Django and open doors to lucrative opportunities in web development.

    Start Learning With EMI Payment Options

    What is Encapsulation in Python?

    The concept of encapsulation is the same in all object-oriented programming languages. The difference is seen when the concepts are applied to particular languages.

    Compared to languages like Java that offer access modifiers (public or private) for variables and methods, Python provides access to all the variables and methods globally.

    Check the below demonstration of how variables can easily be accessed.

    class Person:
        def __init__(self, name, age=0):
            self.name = name
            self.age = age
        def display(self):
            print(self.name)
            print(self.age)
    person = Person('Dev', 30)
    #accessing using class method
    person.display()
    #accessing directly from outside
    print(person.name)
    print(person.age)

    Output

    Dev
    30
    Dev
    30

    Since we do not have access modifiers in Python, we will use a few different methods to control the access of variables within a Python program.


    Methods to Control Access

    There are multiple methods that are offered by Python to limit variable and method access across the program. Let’s go over the methods in detail.

    Using Single Underscore

    A common Python programming convention to identify a private variable is by prefixing it with an underscore. Now, this doesn’t really make any difference on the compiler side of things. The variable is still accessible as usual. But being a convention that programmers have picked up on, it tells other programmers that the variables or methods have to be used only within the scope of the class.

    See the below example:

    class Person:
        def __init__(self, name, age=0):
            self.name = name
            self._age = age
        def display(self):
            print(self.name)
            print(self._age)
    person = Person('Dev', 30)
    #accessing using class method
    person.display()
    #accessing directly from outside
    print(person.name)
    print(person._age)

    Output

    Dev
    30
    Dev
    30

    It’s clear that the variable access is unchanged. But can we do anything to really make it private? Let’s have a look further.

     


    🚀 Start Coding Today! Enroll Now with Easy EMI Options. 💳✨

    Gain expertise in Django and open doors to lucrative opportunities in web development.

    Start Learning With EMI Payment Options

    Using Double Underscores

    If you want to make class members i.e. methods and variables private, then you should prefix them with double underscores. But Python offers some sort of support to the private modifier. This mechanism is called Name mangling. With this, it is still possible to access the class members from outside it.

    Name Mangling

    In Python, any identifier with __Var is rewritten by a python interpreter as _Classname__Var, and the class name remains as the present class name. This mechanism of changing names is called Name Mangling in Python.

    In the below example, in Class person, the age variable is changed and it’s prefixed by leading double underscores.

    class Person:
        def __init__(self, name, age=0):
            self.name = name
            self.__age = age
        def display(self):
            print(self.name)
            print(self.__age)
    person = Person('Dev', 30)
    #accessing using class method
    person.display()
    #accessing directly from outside
    print('Trying to access variables from outside the class ')
    print(person.name)
    print(person.__age)

    Output

    Dev
    30
    Trying to access variables from outside the class
    Dev
    Traceback (most recent call last):
      File "Person.py", line 16, in <module>
        print(person.__age)
    AttributeError: 'Person' object has no attribute '__age'

    You can observe that variables are still be accessed using methods, which is a part of the class. But you cannot access age directly from outside, as it is a private variable.

    “Experience the power of our web development course with a free demo – enroll now!”

    Using Getter and Setter methods to access private variables

    If you want to access and change the private variables, accessor (getter) methods and mutators(setter methods) should be used, as they are part of Class.

    class Person:
        def __init__(self, name, age=0):
            self.name = name
            self.__age = age
        def display(self):
            print(self.name)
            print(self.__age)
        def getAge(self):
            print(self.__age)
        def setAge(self, age):
            self.__age = age
    person = Person('Dev', 30)
    #accessing using class method
    person.display()
    #changing age using setter
    person.setAge(35)
    person.getAge()

    Output

    Dev
    30
    35

    “Get hands-on with our python course – sign up for a free demo!”

    Benefits of Encapsulation in Python

    Encapsulation ensures better data flow and also protects the data from outside sources. The concept of encapsulation makes the code self-sufficient. It is very helpful in the implementation level, as it prioritizes the ‘how’ type questions, leaving behind the complexities. You should hide the data in the unit to make encapsulation easy and also to secure the data.

    What is the need for Encapsulation in Python

    The following reasons show why developers find the Encapsulation handy and why the Object-Oriented concept is outclassing many programming languages.

    • Encapsulation helps in achieving the well-defined interaction in every application.
    • The Object-Oriented concept focuses on the reusability of code in Python. (DRY – Don’t Repeat Yourself).
    • The applications can be securely maintained.
    • It ensures the flexibility of the code through a proper code organization.
    • It promotes a smooth experience for the users without exposing any back-end complexities.
    • It improves the readability of the code. Any changes in one part of the code will not disturb another.
    • Encapsulation ensures data protection and avoids the access of data accidentally.

    Encapsulation in Python is, the data is hidden outside the object definition. It enables developers to develop user-friendly experience. This is also helpful in securing data from breaches, as the code is highly secured and cannot be accessed by outside sources.

    Main Concepts of Object-Oriented Programming (OOPs)

    • Class
    • Objects
    • Polymorphism
    • Encapsulation
    • Inheritance
    • Data Abstraction

    OOPs 

    Class

    A class is a collection of objects. A class contains the blueprints or the prototype from which the objects are being created. It is a logical entity that contains some attributes and methods.

    To understand the need for creating a class let’s consider an example, let’s say you wanted to track the number of dogs that may have different attributes like breed, age. If a list is used, the first element could be the dog’s breed while the second element could represent its age. Let’s suppose there are 100 different dogs, then how would you know which element is supposed to be which? What if you wanted to add other properties to these dogs? This lacks organization and it’s the exact need for classes.

    Some points on Python class:

    • Classes are created by keyword class.
    • Attributes are the variables that belong to a class.
    • Attributes are always public and can be accessed using the dot (.) operator. Eg.: Myclass.Myattribute

    Class Definition Syntax:

    class ClassName:
       # Statement-1
       .
       .
       .
       # Statement-N

    Example: Creating an empty Class in Python

    # Python3 program to
    # demonstrate defining
    # a class
    class Dog:
        pass

    In the above example, we have created a class named dog using the class keyword.

    “Ready to take your python skills to the next level? Sign up for a free demo today!”

    Objects

    The object is an entity that has a state and behavior associated with it. It may be any real-world object like a mouse, keyboard, chair, table, pen, etc. Integers, strings, floating-point numbers, even arrays, and dictionaries, are all objects. More specifically, any single integer or any single string is an object. The number 12 is an object, the string “Hello, world” is an object, a list is an object that can hold other objects, and so on. You’ve been using objects all along and may not even realize it.

    An object consists of :

    • State: It is represented by the attributes of an object. It also reflects the properties of an object.
    • Behavior: It is represented by the methods of an object. It also reflects the response of an object to other objects.
    • Identity: It gives a unique name to an object and enables one object to interact with other objects.

    Example: Creating an object

    obj = Dog()

    This will create an object named obj of the class Dog defined above. Before diving deep into objects and class let us understand some basic keywords that will be used while working with objects and classes.

    The self

    1. Class methods must have an extra first parameter in the method definition. We do not give a value for this parameter when we call the method, Python provides it.
    2. If we have a method that takes no arguments, then we still have to have one argument.
    3. This is similar to this pointer in C++ and this reference in Java.

    When we call a method of this object as myobject.method(arg1, arg2), this is automatically converted by Python into MyClass.method(myobject, arg1, arg2) – this is all the special self is about.

    The __init__ method

    The __init__ method is similar to constructors in C++ and Java. It is run as soon as an object of a class is instantiated. The method is useful to do any initialization you want to do with your object.

    Now let us define a class and create some objects using the self and __init__ method.

    “Experience the power of our web development course with a free demo – enroll now!”

    Example 1: Creating a class and object with class and instance attributes

    class Dog:
        # class attribute
        attr1 = "mammal"
        # Instance attribute
        def __init__(self, name):
            self.name = name
    # Driver code
    # Object instantiation
    Rodger = Dog("Rodger")
    Tommy = Dog("Tommy")
    # Accessing class attributes
    print("Rodger is a {}".format(Rodger.__class__.attr1))
    print("Tommy is also a {}".format(Tommy.__class__.attr1))
    # Accessing instance attributes
    print("My name is {}".format(Rodger.name))
    print("My name is {}".format(Tommy.name))

    Output

    Rodger is a mammal
    Tommy is also a mammal
    My name is Rodger
    My name is Tommy

    Example 2: Creating Class and objects with methods

    class Dog:
        # class attribute
        attr1 = "mammal"
        # Instance attribute
        def __init__(self, name):
            self.name = name
            
        def speak(self):
            print("My name is {}".format(self.name))
    # Driver code
    # Object instantiation
    Rodger = Dog("Rodger")
    Tommy = Dog("Tommy")
    # Accessing class methods
    Rodger.speak()
    Tommy.speak()

    Output

    My name is Rodger
    My name is Tommy

    Inheritance

    Inheritance is the capability of one class to inherit the properties from another class. The class that derives properties is called the derived class or child class and the class from which the properties are being derived is called the base class or parent class. The benefits of inheritance are:

    • It represents real-world relationships well.
    • It provides the reusability of a code. We don’t have to write the same code again and again. It also allows us to add more features to a class without modifying it.
    • It is transitive in nature, which means that if class B inherits from another class A, then all the subclasses of B would automatically inherit from class A.

    Types of Inheritance 

    Single Inheritance:
    Single-level inheritance enables a derived class to inherit characteristics from a single-parent class.

    Multilevel Inheritance:
    Multi-level inheritance enables a derived class to inherit properties from an immediate parent class which in turn inherits properties from his parent class.

    Hierarchical Inheritance:
    Hierarchical level inheritance enables more than one derived class to inherit properties from a parent class.

    Multiple Inheritance:
    Multiple level inheritance enables one derived class to inherit properties from more than one base class.

    Example: Inheritance in Python

     

    # Python code to demonstrate how parent constructors
    # are called.
    # parent class
    class Person(object):
        # __init__ is known as the constructor
        def __init__(self, name, idnumber):
            self.name = name
            self.idnumber = idnumber
        def display(self):
            print(self.name)
            print(self.idnumber)
            
        def details(self):
            print("My name is {}".format(self.name))
            print("IdNumber: {}".format(self.idnumber))
        
    # child class
    class Employee(Person):
        def __init__(self, name, idnumber, salary, post):
            self.salary = salary
            self.post = post
            # invoking the __init__ of the parent class
            Person.__init__(self, name, idnumber)
            
        def details(self):
            print("My name is {}".format(self.name))
            print("IdNumber: {}".format(self.idnumber))
            print("Post: {}".format(self.post))
    # creation of an object variable or an instance
    a = Employee('Rahul', 886012, 200000, "Intern")
    # calling a function of the class Person using
    # its instance
    a.display()
    a.details()

    Output

    Rahul
    886012
    My name is Rahul
    IdNumber: 886012
    Post: Intern

    In the above, we have created two classes i.e. Person (parent class) and Employee (Child Class). The Employee class inherits from the Person class. We can use the methods of the person class through employee class as seen in the display function in the above code. A child class can also modify the behavior of the parent class as seen through the details() method.

    “Get hands-on with our python course – sign up for a free demo!”

    Polymorphism

    Polymorphism simply means having many forms. For example, we need to determine if the given species of birds fly or not, using polymorphism we can do this using a single function.

    Example: Polymorphism in Python

    class Bird:
      
        def intro(self):
            print("There are many types of birds.")
        def flight(self):
            print("Most of the birds can fly but some cannot.")
    class sparrow(Bird):
      
        def flight(self):
            print("Sparrows can fly.")
    class ostrich(Bird):
        def flight(self):
            print("Ostriches cannot fly.")
    obj_bird = Bird()
    obj_spr = sparrow()
    obj_ost = ostrich()
    obj_bird.intro()
    obj_bird.flight()
    obj_spr.intro()
    obj_spr.flight()
    obj_ost.intro()
    obj_ost.flight()

    Output

    There are many types of birds.
    Most of the birds can fly but some cannot.
    There are many types of birds.
    Sparrows can fly.
    There are many types of birds.
    Ostriches cannot fly.

    Encapsulation

    Encapsulation is one of the fundamental concepts in object-oriented programming (OOP). It describes the idea of wrapping data and the methods that work on data within one unit. This puts restrictions on accessing variables and methods directly and can prevent the accidental modification of data. To prevent accidental change, an object’s variable can only be changed by an object’s method. Those types of variables are known as private variables.

    A class is an example of encapsulation as it encapsulates all the data that is member functions, variables, etc.

    Encapsulation in Python

    Example: Encapsulation in Python

    # Python program to
    # demonstrate private members
    # Creating a Base class
    class Base:
        def __init__(self):
            self.a = "GeeksforGeeks"
            self.__c = "GeeksforGeeks"
    # Creating a derived class
    class Derived(Base):
        def __init__(self):
            # Calling constructor of
            # Base class
            Base.__init__(self)
            print("Calling private member of base class: ")
            print(self.__c)
    # Driver code
    obj1 = Base()
    print(obj1.a)
    # Uncommenting print(obj1.c) will
    # raise an AttributeError
    # Uncommenting obj2 = Derived() will
    # also raise an AtrributeError as
    # private member of base class
    # is called inside derived class

    Output

    GeeksforGeeks

    In the above example, we have created the c variable as the private attribute. We cannot even access this attribute directly and can’t even change its value.

    Data Abstraction 

    It hides the unnecessary code details from the user. Also,  when we do not want to give out sensitive parts of our code implementation , data abstraction came.

    Data Abstraction in Python can be achieved through creating abstract classes.

    Python and Machine Learning Rectangle

    Conclusion

    • Object-Oriented Programming makes the program easy to understand as well as efficient.
    • Since the class is sharable, the code can be reused.
    • Data is safe and secure with data abstraction.
    • Polymorphism allows the same interface for different objects, so programmers can write efficient code.

    Related Articles

    Introduction to Data Visualization in Python Why Python Is Used For Data Science?
    Guide for getting a job as a Python Developer Python Advanced Interview Questions and Answers
    Best Online Python Course with Certificate What is Type Conversion in Python?
    Share64SendShare

    Feeba Mahin

    Related Posts

    Top 25 Accounting Interview Questions and Answers
    Accounting

    Top 25 Accounting Interview Questions and Answers

    May 17, 2025
    Top 10 English Phrases Every Healthcare Professional Should Know
    Articles

    Top 10 English Phrases Every Healthcare Professional Should Know

    May 17, 2025
    Why Spoken English is Essential for Healthcare Professionals Today
    Articles

    Why Spoken English is Essential for Healthcare Professionals Today

    May 17, 2025
    Next Post
    What Isinstance In Python And How To Implement It,

    What Isinstance In Python And How To Implement It?

    More to Explore

    1. Future of Python Developers
    2. Python Online Course with 100% Placement
    3. Steps To Code A Video Conferencing App Using Python
    4. Python Advanced Interview Questions and Answers
    5. Introduction to Data Visualization in Python
    6. Python developer – Skills, Courses, Job Roles
    7. Python Developer Salary in India
    8. Method Overloading in Python

    Practice Programs

    1. Program for Finding Factorial of a Number in Python
    2. Python Program to Convert Decimal to Binary Number
    3. Python Program for Fibonacci Series
    4. Prime Number Program in Python
    5. Python Program to Check Armstrong Number

    Python Training in Different Cities

    1. Python Training in Kochi
    2. Python Training in Trivandrum
    3. Python Training in Calicut

    Free Tutorials For You

    1. SQL Tutorial for Beginners PDF
    2. Python Tutorial for Beginners in Hindi
    3. GIT and GITHUB Tutorial for Beginners in Hindi
    4. HTML Exercises to Practice
    5. JavaScript Tutorial in Tamil
    6. DSA Practice Series
    7. Microsoft Excel Malayalam Tutorial
    8. Learn Bootstrap in Tamil
    9. Introduction to CSS in Malayalam
    10. Introduction to JavaScript in Malayalam
    11. Java Programming Notes PDF
    12. Introduction to HTML in Malayalam

    Courses

    • Data Science Course
    • Full Stack Developer Course
    • Software Testing Course
    • Data Science Course in Malayalam
    • Full Stack Developer Course in Malayalam
    • Full Stack Developer Course in Hindi
    • Full Stack Developer Course in Tamil
    • Full Stack Developer Course in Telugu
    • Full Stack Developer Course in Kannada
    • Python Programming Course
    • Practical Accounting Course
    • Structural Design Course
    • Quantity Surveying Course
    • Embedded Systems Course in Kerala
    • BIM Course
    • MEP Course
    • MEP QS Course
    • Stock Market Course
    • Stock Market Course in Malayalam
    • Stock Market Course in Tamil
    • Stock Market Course in Kannada
    • Forex Trading Course
    • Mutual Funds Course
    • PwC Edge : Strategic Accounting and Finance Programme
    • SAP FICO Training
    • SAP MM Training
    • SAP SD Training
    • ACCA Online Course
    • HR Management Course

    Company

    • Become a teacher
    • Login to Entri Web

    Spoken English Courses

    • Spoken English Course
    • Spoken English Course in Malayalam
    • Spoken English Course in Hindi
    • Spoken English Course in Tamil
    • Spoken English Course in Telugu
    • Spoken English Course in Kannada
    • Spoken English Course for Housewives
    • Spoken English Course for Working Professionals
    • Spoken English Course for School Students
    • Spoken English Course for College Students
    • Spoken English Course for Job Seekers
    • AI Powered Spoken English Course

    Quick Links

    • Explore Free Courses
    • Aptitude Questions
    • Articles
    • Videos
    • Entri Daily Quiz Practice
    • Current Affairs & GK
    • News Capsule – eBook
    • Preparation Tips
    • Kerala PSC Gold
    • Entri Skilling
    • Kerala PSC

    Other Courses

    • OET Coaching Classes
    • DHA Course
    • Nurse Recruitment Abroad
    • Montessori Teachers Training
    • Performance Marketing Course
    • German Language Course
    • Yoga Teacher Training Course
    • Digital Marketing Course
    • Options Trading Course
    • German Language A1 Course
    • German Language A2 Course
    • German Language B1 Course
    • German Language B2 Course
    • Diploma in Early Childhood Care and Education
    • Hospital and Healthcare Administration
    • Business Administration & Hospital Management
    • Hospital and Healthcare Administration

    Popular Exam

    • IBPS Exam
    • SBI Exam
    • Railway RRB Exam
    • Kerala PSC
    • Tamil Nadu PSC
    • Telangana PSC
    • Andhra Pradesh PSC
    • MPPSC
    • UPPSC
    • Karnataka PSC
    • Staff Selection Commission Exam
    • GATE

    © 2023 Entri.app - Privacy Policy | Terms of Service

    No Result
    View All Result
    • Kerala PSC
      • Kerala PSC General
        • Kerala PSC Exams
        • KAS Exam
        • Kerala PSC VEO Notification
        • Kerala Police SI
        • Kerala PSC LDC Notification
        • Kerala PSC Village Field Assistant Notification
        • Kerala PSC LD Typist Notification
        • Kerala PSC Food Safety Officer
        • Kerala PSC Excise Inspector Notification
        • Kerala PSC BDO Notification
        • Kerala PSC CPO Notification
        • Kerala PSC LGS Notification
        • Fire and Rescue Officer
        • Women Fire and Rescue Officer
      • Kerala PSC Teaching
        • Kerala PSC HSA
        • Kerala PSC HSST
        • KTET
        • LP/UP Assistant
        • KVS
        • Railway Teacher
      • Kerala PSC Technical
        • LSGD AE
        • Draftsman/Overseer
        • IEO
        • ATP
        • Polytechnic Lecturer
        • AE Electronics
        • Assistant Engineer
    • Banking
      • IBPS PO Notification
      • IBPS Clerk Notification
      • SBI PO Notification
      • SBI Clerk Notification
      • SBI SO Notification
      • SBI Apprentice Notification
      • Canara Bank PO Notification
      • Indian Bank PO Notification
      • RBI Assistant Notification
      • RBI Office Attendant Notification
      • IBPS RRB Notification
      • IBPS RRB Office Assistant Notification
    • Skilling
      • Coding
      • Spoken English
      • Stock Market
        • Share Market Today News
        • Share Market Analysis
      • Digital Marketing
      • Accounting Course
      • SAP
      • OET
      • German
      • IELTS
      • Quantity Survey
      • MEP
      • Structural Design
      • Montessori
      • Yoga Teaching
      • Oil and Gas
    • Courses
      • Data Science Course
        • Data Science Malayalam
        • Data Science Course in Tamil
        • Data Science Course in Telugu
        • Data Science Training in Kochi
        • Data Science Training in Trivandrum
        • Data Science Course in Calicut
        • Data Science Training in Thrissur
      • Data Analytics Course
        • Data Analytics Course in Malayalam
        • Data Analytics Course in Tamil
        • Data Analytics Course in Telugu
      • Technical Upskilling
        • Quantity Surveying Course
        • Structural Design Course
        • BIM Course in Kerala
        • MEP Course
        • Embedded System Course
        • MEP Quantity Surveying Course
        • MEP Course in Kochi
        • Quantity Surveyor Course in Tamil
        • Quantity Surveying Course in Telugu
        • Quantity Surveyor Course in Hyderabad
        • Quantity Surveying Course in Chennai
        • MEP Design Course in Kerala
        • HVAC Course
        • Steel Structure Design Course
        • RCC Design Course
      • Full Stack Developer Course
        • Full Stack Development Malayalam
        • Full Stack Development Hindi
        • Full Stack Development Tamil
        • Full Stack Development Telugu
        • Full Stack Development Kannada
      • Stock Market Course
        • Stock Market Course in Malayalam
        • Stock Market Course in Tamil
        • Stock Market Course in Kannada
        • Options Trading Course
      • Mutual Funds Course
      • Forex Trading Course
      • Spoken English Course
        • Spoken English Course in Malayalam
        • Spoken English Course in Hindi
        • Spoken English Course in Telugu
        • Spoken English Course in Tamil
        • Spoken English Course in Kannada
      • Python Programming Course
      • Software Testing Course
        • Software Testing Course in Malayalam
        • Software Testing Course in Tamil
        • Software Testing Course in Telugu
      • AWS Solutions Architect Associate Course
      • PwC Edge : Strategic Accounting and Finance Programme
      • Practical Accounting Course
        • Accounting Course in Malayalam
        • Accounting Course in Tamil
        • Tally Course
        • Taxation Course
        • UAE Accounting
        • GST Course
        • Zoho Books Training
        • GST Practitioner Course in Kerala
        • GCC VAT Course
      • ACCA Training Online
        • ACCA Course in Kerala
      • SAP Training Courses
        • SAP FICO Course
        • SAP MM Course
        • SAP SD Training
        • SAP FICO Course in Tamil
        • SAP MM Course in Tamil
      • HR Management Course
      • Performance Marketing Course
      • Mern Stack Developer Course
        • Full Stack Developer Course in Kochi
        • Full Stack Developer Course in Trivandrum
        • Full Stack Developer Course in Calicut
        • Full Stack Developer Course in Pune
        • Full Stack Developer Course in Bangalore
        • Full Stack Developer Course in Hyderabad
        • Full Stack Developer Course in Chennai
        • Full Stack Developer Course in Indore
        • Full Stack Developer Course in Jaipur
        • Full Stack Developer Course in Coimbatore
      • Digital Marketing Training
        • Digital Marketing Course in Kochi
        • Digital Marketing Course in Trivandrum
        • Digital Marketing Course in Calicut
        • Digital Marketing Course in Kollam
        • Digital Marketing Course in Thrissur
        • Digital Marketing Course in Kottayam
        • Digital Marketing Course in Kannur
      • Montessori Teacher Training
        • Montessori Teacher Training in Calicut
        • Montessori Teacher Training in Kochi, Ernakulam
        • Montessori Teacher Training in Trivandrum
        • Montessori Teacher Training in Kollam
        • Montessori Teacher Training in Malayalam
        • Montessori Teacher Training in Kannada
      • Other Courses
        • German Language Course
        • OET Coaching
        • DHA Course
        • MOH Exam Coaching
        • Nurses Recruitment Abroad
        • FMGE Coaching
        • ChatGPT Course
        • Forex Trading Course
        • Yoga Teacher Training Course
        • Diploma in Early Childhood Care and Education
        • Business Administration & Hospital Management Course
        • Hospital and Healthcare Administration
        • AI for Teachers Course
    • Others
      • Railway
        • RRB Technician Notification
        • RRB JE Notification
        • RRB ALP Notification
        • RRB NTPC Notification
        • RRB RPF Notification
        • RRB RPF SI Notification
        • RRB RPF Constable Notification
        • RRB Group D Notification
        • RRB RPSF SI Notification
        • RRB SSE Notification
      • SSC
        • SSC CPO Notification
        • SSC MTS Notification
        • SSC CGL Notification
        • SSC CHSL Notification
        • SSC GD Constable Notification
        • SSC Stenographer Notification
        • SSC JE Notification
        • SSC CAPF Notification
        • SSC JHT Notification
        • Delhi Police Constable Notification
        • Delhi Police SI Notification
      • GATE
      • MAT
      • KMAT
        • KMAT Kerala 2024
      • TET
        • APTET
        • CTET
        • DSSSB
        • Karnataka TET
        • Kerala TET
        • KVS
        • MPTET
        • SUPER TET
        • TNTET
        • TSTET
        • UPTET
      • UPSC
        • UPSC CAPF Notification
        • UPSC CDS Notification
        • UPSC NDA Notification
        • UPSC Civil service Notification
    • Free Learn
      • Free Courses
        • Free Coding Courses
        • Free Accounting Courses
        • Free Digital Marketing Courses
        • Engineering Upskilling Courses
        • Free Hospital Administration Courses
        • Free OET Training
        • Free SAP Courses
        • Free Teachers Training Courses
        • Free Trading Courses
      • Question Answer
      • Aptitude Questions
      • Webinars
    • Test Prep
      • Kerala PSC Coaching
        • KPSC Degree Level Exam Preparation
        • Kerala PSC 12th Level Exam Preparation
        • Kerala PSC 10th Level Exam Preparation
        • KAS Coaching
        • Kerala PSC LDC Coaching
        • Kerala PSC LD Typist Coaching
        • Kerala PSC Fireman Coaching
        • KSFE Assistant Exam Preparation
        • Secretariat Office Attendant Coaching
        • Secretariat Assistant Coaching
        • Kerala PSC SI Exam Coaching
        • Khadi Board LDC Exam Preparation
        • Devaswom Board LDC Coaching
        • University LGS Exam Preparation
        • University Assistant Exam Coaching
        • KPSC Scientific Officer Exam Coaching
        • KPSC Probation Officer Grade II
        • KPSC Food Safety Officer Coaching
        • KWA Sanitary Chemist Coaching
        • KPSC Diary Farm Instructor Exam Coaching
        • Kerala PSC KWA Lab Assistant Exam Coaching
        • Kerala PSC ICDS Supervisor Exam Coaching
        • KPSC Finger Print Searcher Coaching
        • Kerala PSC Welfare Officer Gr. II Exam Coaching
        • KPSC Assistant Dental Surgeon Coaching
      • KPSC Teaching Exams
        • HSA Exam Preparation
        • KPSC HSA Social Science Coaching
        • KPSC HSA Physical Science Coaching
        • KPSC HSA English Coaching
        • KPSC Junior Language Teacher Hindi
        • KTET Coaching
        • SET Coaching
        • LP/UP Assistant Exam Coaching
        • HSST Exam Preparation
        • HSST Commerce Exam Coaching
        • Kerala PSC Lecturer in Diet Coaching
        • KVS PGT/TGT Coaching
      • Kerala PSC Technical Exams Coaching
        • Assistant Engineer Electrical Exam Coaching
        • Assistant Engineer Electronics Coaching
        • Assistant Engineer Mechanical Coaching
        • Kerala PSC Industries Extension Officer Coaching
        • KPSC LSGD AE Exam Coaching
        • KPSC Civil Engineering Exam Coaching
        • KPSC Mechanical Engineering Exam Coaching
        • KPSC Electrical Engineering Exam Coaching
        • KPSC Electronics Engineering Exam Coaching
        • KPSC Technical Computer Science Coaching
        • KPSC Tradesman Turning Coaching
        • Kerala PSC Overseer Exam Coaching
        • KPSC Assistant Town Planner Coaching
        • Lecturer in Polytechnic Electronics Coaching
      • Teaching Exams Coaching
        • CSIR NET Exam Coaching
        • EMRS Coaching
        • CTET Exam Online Coaching
      • IELTS Training Online
      • Bank Exam Coaching Online
        • SEBI Grade A Coaching
        • IBPS SO Online Coaching
        • IBPSC PO Online Coaching
        • IBPSC Clerk Online Coaching
        • SBI PO Coaching
        • SBI Clerk Online Coaching
        • SBI Apprentice Class
        • SBI SO Online Coaching
        • RBI Grade B Coaching
        • RBI Assistant Coaching
        • CSEB Exam Coaching
        • IBPS RRB Coaching
        • IBPS RRB PO Coaching
        • Canara Bank Po Exam Coaching
        • Kerala Gramin Bank Coaching
        • Kerala Bank Exam Coaching
        • JCI Exam Coaching
        • NABARD Grade A Coaching
        • LIC AAO Coaching Online
      • UPSC Online Coaching
        • UPSC CAPF Online Coaching
      • SSC Online Coaching
        • SSC JE Online Coaching
        • SSC CGL Coaching
        • SSC CGL AAO Coaching
        • SSC CGL CBI Inspector Coaching
        • SSC CHSL Coaching
        • SSC MTS Coaching
        • SSC Stenographer Coaching
        • SSC GD Online Coaching
      • RRB Exams Coaching
        • RRB RPF Exam Coaching
        • RRB NTPC Exam Coaching
        • RRB JE Online Coaching
        • RRB JE Electronics Coaching
        • RRB ALP Exam Coaching
        • RRB Technician Exam Coaching
      • CAT Online Coaching
      • CMAT Online Coaching
      • XAT Exam Coaching
      • GATE Online Coaching
        • GATE CE Online Coaching
        • GATE ME Online Coaching
        • GATE EE Online Coaching
      • NMAT Exam Coaching
      • AAI ATC Jr Executive Coaching
      • Cochin Shipyard Executive Trainee Coaching
      • BEL Probationary Engineer Coaching
      • HPCL Junior Executive Coaching

    © 2023 Entri.app - Privacy Policy | Terms of Service

    Chat