Skip to main content

Python OOP Concepts: Complete Guide with Examples

 

✍️Introduction

OOP (Object-Oriented Programming) is a programming approach that uses objects and classes.
Python fully supports OOP, which helps in writing clean, reusable, and scalable code.

Object-Oriented Programming (OOP) organizes programs into objects that contain both data and functions.
It helps model real-world entities like students, cars, or accounts in the form of classes and objects.

OOP makes programs easier to manage by improving code reusability, modularity, and maintainability, which is why it is widely used in large software projects.


What is OOP?

Object-Oriented Programming (OOP) is a programming style that organizes code using classes and objects to represent real-world entities.

In OOP, a class acts as a blueprint that defines properties and behaviors, while objects are instances of that class.

This approach helps structure programs logically and makes code easier to reuse and maintain.

OOP is based on:
  • Objects → real-world entities

  • Classes → blueprint of objects

Classes and objects are the two core concepts in object-oriented programming.

Example:

Class = Student
Object = Rutuja , Tushar


1️⃣ Class in Python :

A class in Python is a blueprint used to create objects with similar properties and behaviors.

To create a class in Python, we use the class keyword followed by the class name.
A class contains variables (attributes) and functions (methods) that define the characteristics of objects created from it.

Syntax for ceating class:

class ClassName: statements

Example:

class Student:        # Defines a class named Student name = "Rutuja" # Class attribute name age = 20          # Class attribute age

The class only defines the structure; objects are created from the class to use these attributes.

There is no output because we only created a class and did not create any object or print anything.


2️⃣ Object in Python :

An object is an instance of a class. It represents a real-world entity and contains data (attributes) and functions (methods) defined inside the class.

When a class is created, no memory is allocated until an object is created.
An object allows us to access the variables and methods of a class.
We can create multiple objects from one class, and each object can have different values.

Example:

class Student: # Defines a class named Student name = "Rutuja" # Class attribute name age = 20 # Class attribute age s1 = Student() # Creates an object of Student class print(s1.name) # Prints name print(s1.age) # Prints age

Output:
Rutuja 20

"Code executed successfully" 

Explanation:

  • s1 = Student() creates an object of the Student class.

  • s1.name prints Rutuja

  • s1.age prints 20



3️⃣__init__() Constructor in Python :

A constructor is a special method in a class that is automatically called when an object is created. In Python, the constructor is written as __init__() and is used to initialize object data (attributes).

  • The __init__() method runs automatically when a new object is created.

  • It helps assign initial values to object variables.

  • The self parameter refers to the current object.

  • Constructors make it easy to set up objects with different values.

Example:

class Student:

def __init__(self, name, age): self.name = name # Initialize name attribute self.age = age # Initialize age attribute # Creating an object of Student class s1 = Student("Rutuja", 20) # Printing object data print(s1.name) print(s1.age)

Output:
Rutuja 20

"Code executed successfully" 


4️⃣ self Keyword :

self is a reference to the current object of the class. It is used to access the variables and methods of the class.
  • self represents the current instance (object).

  • It is used inside class methods to access object data.

  • Every method in a class must have self as the first parameter.

  • It is not a keyword, but a commonly used convention.

Example:

class Student:
    def __init__(self, name, age):
        self.name = name                                # self refers to current object
        self.age = age

    def show(self):
        print("Name:", self.name)                  # Accessing variable using self
        print("Age:", self.age)

# Creating object
s1 = Student("Rutuja", 20)

# Calling method
s1.show()

Output:
Rutuja 20

"Code executed successfully" 


5️⃣ Methods in Class :

Methods are functions that are defined inside a class and are used to perform operations on objects.

  • Methods define the behavior of objects.

  • They are written inside a class.

  • Methods usually use self to access object data.

  • They are called using objects of the class.

Example:

# Creating a class named Student class Student: # Defining a method inside the class def show(self):                           # 'self' refers to the current object print("Welcome Student")                 # This line prints a message # Creating an object of Student class s1 = Student() # Calling the show() method using the object s1.show()

Output:
Welcome Student

"Code executed successfully" 

Note:self must be written as the first parameter in every class method so the method can access

the object's data.


6️⃣ Four Pillars of OOP :

Object-Oriented Programming (OOP) is based on four main principles called the Four Pillars of OOP. These pillars help in organizing code, improving reusability, and making programs easier to manage.

The four pillars are:

  1. Encapsulation
    Encapsulation means wrapping data (variables) and methods (functions) together inside a class.
    It helps in protecting data from direct access and keeps it safe.

  2. Inheritance
    Inheritance allows one class to use the properties and methods of another class.
    It helps in reusing code and reducing duplication.

  3. Polymorphism
    Polymorphism means "many forms".
    It allows the same function or method name to behave differently in different situations.

  4. Abstraction
    Abstraction means hiding unnecessary details and showing only important features.
    It helps in reducing complexity and makes code easier to understand.

In short:
The four pillars of OOP make programs secure, reusable, flexible, and easy to maintain.


🔹 1. Encapsulation :

Encapsulation means binding data (variables) and methods (functions) together inside a class.
It is used to protect data and prevent direct access from outside the class.

Encapsulation helps in keeping the data safe and controlled by allowing access only through methods.

Example:

class Account: def __init__(self, balance): # Constructor to initialize balance self.balance = balance # Data (variable) inside class def show_balance(self): # Method to access data print("Balance:", self.balance) acc1 = Account(5000) # Creating object acc1.show_balance() # Calling method


Output:
Balance: 5000

"Code executed successfully" 

✔ Improves security
✔ Data protection
✔ Easy data management

 Note:Encapsulation controls how data is accessed and modified.


🔹 2. Inheritance :

Inheritance is a feature of OOP where one class (child class) inherits properties and methods from another class (parent class).

It allows code to be reused and helps in creating a relationship between classes.
The child class can use the parent class methods without rewriting the code.

Example:

class Parent: def show(self): # Method in parent class print("Parent class") class Child(Parent): # Child class inherits Parent class pass # No new code, uses Parent methods c = Child() # Creating object of Child class c.show() # Calling inherited method


Output:

Parent class

"Code executed successfully" 

✔ Code reusability ✔ Saves time and effort
✔ Creates parent-child relationship

Note:The child class can access all public methods of the parent class.


🔹 3. Polymorphism :

Polymorphism means “many forms.”

In OOP, polymorphism allows the same method name to behave differently depending on the object.

It is commonly achieved using method overriding or method overloading (Python mainly uses overriding).

Polymorphism makes code flexible and easier to extend because the same function name can work in different ways.

Example:

class A: def show(self): # Method in class A print("Class A") class B(A): def show(self): # Overriding method of class A print("Class B") obj = B() # Creating object of class B obj.show() # Calls method of class B


Output:

Class B

"Code executed successfully" 

✔ Same method name ✔ Different behavior ✔ Improves flexibility

Note: If a child class overrides a method, Python will call the child class method

instead of the parent class method.


🔹 4. Abstraction :

Abstraction means hiding the internal implementation details and showing only the important features to the user.

In Python, abstraction is implemented using abstract classes and abstract methods with the help of the abc module.

Abstraction helps in reducing complexity and increases security because the user only sees what is necessary.

✔ Hides unnecessary details
✔ Shows essential features only
✔ Improves code security and structure

Example:

from abc import ABC, abstractmethod # Importing abstract class tools class Vehicle(ABC): # Abstract class @abstractmethod def start(self): # Abstract method pass # No implementation here class Car(Vehicle): # Child class def start(self): # Implementing abstract method print("Car started") c = Car() # Creating object c.start() # Calling method

Output:

Car started

"Code executed successfully" 

Note:An abstract class cannot be used to create objects directly.
The abstract method must be implemented in the child class.


7️⃣ Access Modifiers in Python :

Access modifiers are used to control the visibility of variables and methods in a class.
They help in protecting data and controlling how class members are accessed.

Python does not have strict access control like some other languages, but it uses naming conventions to indicate access levels.

Access modifiers are mainly used for:

  • Data protection

  • Encapsulation

  • Controlling access to variables

  • Improving code security


Modifier            Syntax               Meaning                                
Public          nameAccessible everywhere
Protected_name       Within class & subclass
Private__nameOnly within class

🔹1. Public :

Public members can be accessed from anywhere inside or outside the class.

Example:

class Student:
name = "Rutuja" # Public variable

s = Student()
print(s.name) # Accessible


Output:

Rutuja

"Code executed successfully" 

🔹2. Protected :

Protected members are intended to be used within the class and its subclasses.
(They can still be accessed outside, but it is not recommended.)

Example:

class Student:
_age = 20 # Protected variable

s = Student()
print(s._age) # Possible but not recommended


Output:

20

"Code executed successfully" 

🔹3. Private :

Private members are accessible only inside the class.
They cannot be accessed directly outside the class.

Example:

class Student: __marks = 90 # Private variable def show_marks(self): print("Marks:", self.__marks) # Create object s1 = Student() # Access private variable using method s1.show_marks()

Output:

Marks: 90

"Code executed successfully" 

Accessing Private Variable using Name Mangling

print(s1._Student__marks)

Output

90

Explanation:

  • __marks is a private variable.
  • It cannot be accessed directly like s1.__marks.

  • It can be accessed using a class method or _Student__marks (name mangling).

📝 Note:

  • Public → No underscore

  • Protected → Single underscore _

  • Private → Double underscore __

  • Private variables can only be accessed using class methods.


8️⃣ Real-Life OOP Example :

In this example, Car is a class that represents a real-world car.

class Car:                      # Define a class named Car def __init__(self, brand, price):     # Constructor to initialize object data self.brand = brand              # Assign brand value to object variable self.price = price              # Assign price value to object variable def show(self):              # Method to display car details print(self.brand, self.price)         # Print brand and price of the car c1 = Car("Toyota", 1000000) # Create an object of Car class c1.show()              # Call the show() method


Output:

Toyota 1000000

"Code executed successfully" 


9️⃣ Why Use OOP?

  • Better code structure

  • Easy maintenance

  • Reusability

  • Real-world modeling


❌ Common OOP Mistakes:

  • Forgetting self

  • Wrong indentation

  • Not using constructor properly


Conclusion :

Python OOP makes programs modular, readable, and powerful.
Understanding OOP is essential for real-world applications, interviews, and projects.


💬 Interview Question :

Explain Inheritance vs Polymorphism in your own words ?

Comment below 👇😊


📌 Related Articles :

Comments

popular

What Is Python Programming? Features, Uses and Career Scope.

  ✍️ Introduction Python is one of the most popular and beginner-friendly programming languages in the world today. It is widely used for web development, data science, artificial intelligence, automation, and software development. Because of its simple syntax and powerful features, Python is an excellent choice for students, beginners, and professionals. In this article, you will learn what Python programming is, its key features, real-life uses, and the career opportunities it offers. 🧠 What Is Python Programming? Python is a high-level, interpreted programming language created to make coding easy and readable. It allows developers to write programs using simple English-like statements, which makes it ideal for beginners. Python supports multiple programming styles such as procedural, object-oriented, and functional programming. ⭐ Features of Python Easy to learn and understand Simple and readable syntax Interpreted language Platform independent Large standard l...

what is Python Date and Time ? Complete Guide with Examples:

  ✍️ Introduction Python provides powerful tools to work with dates and times . The most commonly used module is datetime . The datetime module allows Python programs to create, manipulate, format, and perform calculations with dates and times easily. Date and time handling is used in: Logging systems Attendance & billing systems Data analysis Real-time applications How To Import Date and Time Module : In Python, the datetime module is used to work with dates , times , and date–time combinations . It is part of Python’s standard library, so no installation is required. You can import it in different ways depending on your need. import datetime Get Current Date and Time: This code obtains the current system date and time as a single datetime object using the datetime module. Example: import datetime now = datetime.datetime.now() print (now) Output: 2026-02-13 11:25:53.445827 "Code executed successfully"  Get Only Date: This code retrieves t...

Features of Python Programming Language Explained with Examples

✍️ Introduction Python is one of the most popular programming languages because of its powerful and easy-to-use features. It is designed to make programming simple, readable, and efficient. Python is widely used by beginners as well as professionals due to its flexibility and strong community support. In this article, we will discuss the main features of Python programming language in simple English with easy examples. 🧠 What Are Features of Python? Features of Python are the special characteristics that make it different from other programming languages. These features help programmers write clean, readable, and efficient code with less effort. ⭐ Key Features of Python Programming Language 1️⃣ Easy to Learn and Easy to Use Python has a simple syntax that is close to the English language. This makes it very easy for beginners to learn and understand programming concepts. Example: print("Hello, World!") 2️⃣ Interpreted Language Python is an interpreted language, which me...

Python Operators: Types with Examples

 ✍️Introduction In Python, operators are symbols used to perform operations on variables and values. Operators help us do calculations, comparisons, and logical decisions in programs. In this article, you will learn: • What Python operators are • Types of Python operators • Simple examples for each type