Object Oriented Programming is a fundamental concept in Python, empowering developers to build modular, maintainable, and scalable applications. By understanding the core OOP principles (classes, objects, inheritance, encapsulation, polymorphism, and abstraction), programmers can leverage the full potential of Python OOP capabilities to design elegant and efficient solutions to complex problems.
OOPs is a way of organizing code that uses objects and classes to represent real-world entities and their behavior. In OOPs, object has attributes thing that has specific data and can perform certain actions using methods.
OOPs Concepts in Python
- Class in Python
- Objects in Python
- Polymorphism in Python
- Encapsulation in Python
- Inheritance in Python
- Data Abstraction in Python

Python OOPs Concepts
Python Class
A class is a collection of objects. Classes are blueprints for creating objects. A class defines a set of attributes and methods that the created objects (instances) can have.
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. Example: Myclass.Myattribute
Creating a Class
Here, the class keyword indicates that we are creating a class followed by name of the class (Dog in this case).
Python
class Dog:
species = "Canine" # Class attribute
def __init__(self, name, age):
self.name = name # Instance attribute
self.age = age # Instance attribute
Explanation:
- class Dog: Defines a class named Dog.
- species: A class attribute shared by all instances of the class.
- __init__ method: Initializes the name and age attributes when a new object is created.
Note: For more information, refer to python classes.
Python Objects
An Object is an instance of a Class. It represents a specific implementation of the class and holds its own data.
An object consists of:
- State: It is represented by the attributes and reflects the properties of an object.
- Behavior: It is represented by the methods of an object and 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.
Creating Object
Creating an object in Python involves instantiating a class to create a new instance of that class. This process is also referred to as object instantiation.
Python
class Dog:
species = "Canine" # Class attribute
def __init__(self, name, age):
self.name = name # Instance attribute
self.age = age # Instance attribute
# Creating an object of the Dog class
dog1 = Dog("Buddy", 3)
print(dog1.name)
print(dog1.species)
Explanation:
- dog1 = Dog(“Buddy”, 3): Creates an object of the Dog class with name as “Buddy” and age as 3.
- dog1.name: Accesses the instance attribute name of the dog1 object.
- dog1.species: Accesses the class attribute species of the dog1 object.
Note: For more information, refer to python objects.
Self Parameter
self parameter is a reference to the current instance of the class. It allows us to access the attributes and methods of the object.
Python
class Dog:
species = "Canine" # Class attribute
def __init__(self, name, age):
self.name = name # Instance attribute
self.age = age # Instance attribute
dog1 = Dog("Buddy", 3) # Create an instance of Dog
dog2 = Dog("Charlie", 5) # Create another instance of Dog
print(dog1.name, dog1.age, dog1.species) # Access instance and class attributes
print(dog2.name, dog2.age, dog2.species) # Access instance and class attributes
print(Dog.species) # Access class attribute directly
OutputBuddy 3 Canine
Charlie 5 Canine
Canine
Explanation:
- self.name: Refers to the name attribute of the object (dog1) calling the method.
- dog1.bark(): Calls the bark method on dog1.
Note: For more information, refer to self in the Python class
__init__ Method
__init__ method is the constructor in Python, automatically called when a new object is created. It initializes the attributes of the class.
Python
class Dog:
def __init__(self, name, age):
self.name = name
self.age = age
dog1 = Dog("Buddy", 3)
print(dog1.name)
Explanation:
- __init__: Special method used for initialization.
- self.name and self.age: Instance attributes initialized in the constructor.
Class and Instance Variables
In Python, variables defined in a class can be either class variables or instance variables, and understanding the distinction between them is crucial for object-oriented programming.
Class Variables
These are the variables that are shared across all instances of a class. It is defined at the class level, outside any methods. All objects of the class share the same value for a class variable unless explicitly overridden in an object.
Instance Variables
Variables that are unique to each instance (object) of a class. These are defined within the __init__ method or other instance methods. Each object maintains its own copy of instance variables, independent of other objects.
Python
class Dog:
# Class variable
species = "Canine"
def __init__(self, name, age):
# Instance variables
self.name = name
self.age = age
# Create objects
dog1 = Dog("Buddy", 3)
dog2 = Dog("Charlie", 5)
# Access class and instance variables
print(dog1.species) # (Class variable)
print(dog1.name) # (Instance variable)
print(dog2.name) # (Instance variable)
# Modify instance variables
dog1.name = "Max"
print(dog1.name) # (Updated instance variable)
# Modify class variable
Dog.species = "Feline"
print(dog1.species) # (Updated class variable)
print(dog2.species)
OutputCanine
Buddy
Charlie
Max
Feline
Feline
Explanation:
- Class Variable (species): Shared by all instances of the class. Changing Dog.species affects all objects, as it’s a property of the class itself.
- Instance Variables (name, age): Defined in the __init__ method. Unique to each instance (e.g., dog1.name and dog2.name are different).
- Accessing Variables: Class variables can be accessed via the class name (Dog.species) or an object (dog1.species). Instance variables are accessed via the object (dog1.name).
- Updating Variables: Changing Dog.species affects all instances. Changing dog1.name only affects dog1 and does not impact dog2.
Python Inheritance
Inheritance allows a class (child class) to acquire properties and methods of another class (parent class). It supports hierarchical classification and promotes code reuse.
Types of Inheritance:
- Single Inheritance: A child class inherits from a single parent class.
- Multiple Inheritance: A child class inherits from more than one parent class.
- Multilevel Inheritance: A child class inherits from a parent class, which in turn inherits from another class.
- Hierarchical Inheritance: Multiple child classes inherit from a single parent class.
- Hybrid Inheritance: A combination of two or more types of inheritance.
Python
# Single Inheritance
class Dog:
def __init__(self, name):
self.name = name
def display_name(self):
print(f"Dog's Name: {self.name}")
class Labrador(Dog): # Single Inheritance
def sound(self):
print("Labrador woofs")
# Multilevel Inheritance
class GuideDog(Labrador): # Multilevel Inheritance
def guide(self):
print(f"{self.name}Guides the way!")
# Multiple Inheritance
class Friendly:
def greet(self):
print("Friendly!")
class GoldenRetriever(Dog, Friendly): # Multiple Inheritance
def sound(self):
print("Golden Retriever Barks")
# Example Usage
lab = Labrador("Buddy")
lab.display_name()
lab.sound()
guide_dog = GuideDog("Max")
guide_dog.display_name()
guide_dog.guide()
retriever = GoldenRetriever("Charlie")
retriever.display_name()
retriever.greet()
retriever.sound()
Explanation:
- Single Inheritance: Labrador inherits Dog’s attributes and methods.
- Multilevel Inheritance: GuideDog extends Labrador, inheriting both Dog and Labrador functionalities.
- Multiple Inheritance: GoldenRetriever inherits from both Dog and Friendly.
Note: For more information, refer to our Inheritance in Python tutorial.
Python Polymorphism
Polymorphism allows methods to have the same name but behave differently based on the object’s context. It can be achieved through method overriding or overloading.
Types of Polymorphism
- Compile-Time Polymorphism: This type of polymorphism is determined during the compilation of the program. It allows methods or operators with the same name to behave differently based on their input parameters or usage. It is commonly referred to as method or operator overloading.
- Run-Time Polymorphism: This type of polymorphism is determined during the execution of the program. It occurs when a subclass provides a specific implementation for a method already defined in its parent class, commonly known as method overriding.
Code Example:
Python
# Parent Class
class Dog:
def sound(self):
print("dog sound") # Default implementation
# Run-Time Polymorphism: Method Overriding
class Labrador(Dog):
def sound(self):
print("Labrador woofs") # Overriding parent method
class Beagle(Dog):
def sound(self):
print("Beagle Barks") # Overriding parent method
# Compile-Time Polymorphism: Method Overloading Mimic
class Calculator:
def add(self, a, b=0, c=0):
return a + b + c # Supports multiple ways to call add()
# Run-Time Polymorphism
dogs = [Dog(), Labrador(), Beagle()]
for dog in dogs:
dog.sound() # Calls the appropriate method based on the object type
# Compile-Time Polymorphism (Mimicked using default arguments)
calc = Calculator()
print(calc.add(5, 10)) # Two arguments
print(calc.add(5, 10, 15)) # Three arguments
Explanation:
1. Run-Time Polymorphism:
- Demonstrated using method overriding in the Dog class and its subclasses (Labrador and Beagle).
- The correct sound method is invoked at runtime based on the actual type of the object in the list.
2. Compile-Time Polymorphism:
- Python does not natively support method overloading. Instead, we use a single method (add) with default arguments to handle varying numbers of parameters.
- Different behaviors (adding two or three numbers) are achieved based on how the method is called.
Note: For more information, refer to our Polymorphism in Python Tutorial.
Python Encapsulation
Encapsulation is the bundling of data (attributes) and methods (functions) within a class, restricting access to some components to control interactions.
A class is an example of encapsulation as it encapsulates all the data that is member functions, variables, etc.

Types of Encapsulation:
- Public Members: Accessible from anywhere.
- Protected Members: Accessible within the class and its subclasses.
- Private Members: Accessible only within the class.
Code Example:
Python
class Dog:
def __init__(self, name, breed, age):
self.name = name # Public attribute
self._breed = breed # Protected attribute
self.__age = age # Private attribute
# Public method
def get_info(self):
return f"Name: {self.name}, Breed: {self._breed}, Age: {self.__age}"
# Getter and Setter for private attribute
def get_age(self):
return self.__age
def set_age(self, age):
if age > 0:
self.__age = age
else:
print("Invalid age!")
# Example Usage
dog = Dog("Buddy", "Labrador", 3)
# Accessing public member
print(dog.name) # Accessible
# Accessing protected member
print(dog._breed) # Accessible but discouraged outside the class
# Accessing private member using getter
print(dog.get_age())
# Modifying private member using setter
dog.set_age(5)
print(dog.get_info())
Explanation:
- Public Members: Easily accessible, such as name.
- Protected Members: Used with a single _, such as _breed. Access is discouraged but allowed in subclasses.
- Private Members: Used with __, such as __age. Access requires getter and setter methods.
Note: for more information, refer to our Encapsulation in Python Tutorial.
Data Abstraction
Abstraction hides the internal implementation details while exposing only the necessary functionality. It helps focus on “what to do” rather than “how to do it.”
Types of Abstraction:
- Partial Abstraction: Abstract class contains both abstract and concrete methods.
- Full Abstraction: Abstract class contains only abstract methods (like interfaces).
Code Example:
Python
from abc import ABC, abstractmethod
class Dog(ABC): # Abstract Class
def __init__(self, name):
self.name = name
@abstractmethod
def sound(self): # Abstract Method
pass
def display_name(self): # Concrete Method
print(f"Dog's Name: {self.name}")
class Labrador(Dog): # Partial Abstraction
def sound(self):
print("Labrador Woof!")
class Beagle(Dog): # Partial Abstraction
def sound(self):
print("Beagle Bark!")
# Example Usage
dogs = [Labrador("Buddy"), Beagle("Charlie")]
for dog in dogs:
dog.display_name() # Calls concrete method
dog.sound() # Calls implemented abstract method
Explanation:
- Partial Abstraction: The
Dog
class has both abstract (sound
) and concrete (display_name
) methods. - Why Use It: Abstraction ensures consistency in derived classes by enforcing the implementation of abstract methods.
To practice Python OOPs problems, you can refer to our:
To learn more concepts of OOPs refer to:
Python OOPs – FAQs
What are the 4 pillars of OOP Python?
The 4 pillars of object-oriented programming (OOP) in Python (and generally in programming) are:
- Encapsulation: Bundling data (attributes) and methods (functions) that operate on the data into a single unit (class).
- Abstraction: Hiding complex implementation details and providing a simplified interface.
- Inheritance: Allowing a class to inherit attributes and methods from another class, promoting code reuse.
- Polymorphism: Using a single interface to represent different data types or objects.
Is OOP used in Python?
Yes, Python fully supports object-oriented programming (OOP) concepts. Classes, objects, inheritance, encapsulation, and polymorphism are fundamental features of Python.
Is Python 100% object-oriented?
Python is a multi-paradigm programming language, meaning it supports multiple programming paradigms including procedural, functional, and object-oriented programming. While Python is predominantly object-oriented, it also allows for procedural and functional programming styles.
What is __init__
in Python?
__init__
is a special method (constructor) in Python classes. It’s automatically called when a new instance (object) of the class is created. Its primary purpose is to initialize the object’s attributes or perform any setup required for the object.
class MyClass:
def __init__(self, arg1, arg2):
self.arg1 = arg1
self.arg2 = arg2
What is super()
in Python?
super()
is used to call methods of a superclass (parent class) from a subclass (child class). It returns a proxy object that delegates method calls to the superclass. This is useful for accessing inherited methods that have been overridden in a subclass.
class ChildClass(ParentClass):
def __init__(self, arg1, arg2):
super().__init__(arg1) # Calls the __init__() method of the ParentClass
self.arg2 = arg2
Why is self
used in Python?
'self'
is a convention in Python used to refer to the instance of a class (object) itself. It’s the first parameter of instance methods and refers to the object calling the method. It allows methods to access and manipulate attributes (variables) that belong to the instance.
class MyClass:
def __init__(self, name):
self.name = name
def greet(self):
return f"Hello, {self.name}!"
obj = MyClass("Alice")
print(obj.greet()) # Output: Hello, Alice!
Similar Reads
Python OOPs Concepts
Object Oriented Programming is a fundamental concept in Python, empowering developers to build modular, maintainable, and scalable applications. By understanding the core OOP principles (classes, objects, inheritance, encapsulation, polymorphism, and abstraction), programmers can leverage the full p
11 min read
Python Classes and Objects
A class in Python is a user-defined template for creating objects. It bundles data and functions together, making it easier to manage and use them. When we create a new class, we define a new type of object. We can then create multiple instances of this object type. Classes are created using class k
6 min read
Python objects
A class is a user-defined blueprint or prototype from which objects are created. Classes provide a means of bundling data and functionality together. Creating a new class creates a new type of object, allowing new instances of that type to be made. Each class instance can have attributes attached to
2 min read
Class and Object
self in Python class
Self represents the instance of the class. By using the "self" we can access the attributes and methods of the class in Python. It binds the attributes with the given arguments. The reason you need to use self. is because Python does not use the @ syntax to refer to instance attributes. Python decid
6 min read
Class and Instance Attributes in Python
Class attributes: Class attributes belong to the class itself they will be shared by all the instances. Such attributes are defined in the class body parts usually at the top, for legibility. [GFGTABS] Python # Write Python code here class sampleclass: count = 0 # class attribute def increase(self):
2 min read
Create a Python Subclass
In Python, a subclass is a class that inherits attributes and methods from another class, known as the superclass or parent class. When you create a subclass, it can reuse and extend the functionality of the superclass. This allows you to create specialized versions of existing classes without havin
3 min read
Inner Class in Python
Python is an Object-Oriented Programming Language, everything in Python is related to objects, methods, and properties. A class is a user-defined blueprint or a prototype, which we can use to create the objects of a class. The class is defined by using the class keyword. Example of class [GFGTABS] P
5 min read
Python MetaClasses
The key concept of python is objects. Almost everything in python is an object, which includes functions and as well as classes. As a result, functions and classes can be passed as arguments, can exist as an instance, and so on. Above all, the concept of objects let the classes in generating other c
9 min read
Creating Instance Objects in Python
In Python, an instance object is an instantiation of a class, and it is a unique occurrence of that class. Creating instance objects is a fundamental concept in object-oriented programming (OOP) and allows developers to work with and manipulate specific instances of a class. This article will explor
3 min read
Dynamic Attributes in Python
Dynamic attributes in Python are terminologies for attributes that are defined at runtime, after creating the objects or instances. In Python we call all functions, methods also as an object. So you can define a dynamic instance attribute for nearly anything in Python. Consider the below example for
2 min read
Constructors in Python
In Python, a constructor is a special method that is called automatically when an object is created from a class. Its main role is to initialize the object by setting up its attributes or state. The method __new__ is the constructor that creates a new instance of the class while __init__ is the init
3 min read
Why Python Uses 'Self' as Default Argument
In Python, when defining methods within a class, the first parameter is always self. The parameter self is a convention not a keyword and it plays a key role in Pythonâs object-oriented structure. Example: [GFGTABS] Python class Car: def __init__(self, brand, model): self.brand = brand # Set instanc
3 min read
Encapsulation and Access Modifiers
Encapsulation in Python
In Python, encapsulation refers to the bundling of data (attributes) and methods (functions) that operate on the data into a single unit, typically a class. It also restricts direct access to some components, which helps protect the integrity of the data and ensures proper usage. Table of Content En
6 min read
Access Modifiers in Python : Public, Private and Protected
Prerequisites: Underscore (_) in Python, Private Variables in Python Encapsulation is one of the four principles used in Object Oriented Paradigm. It is used to bind and hide data to the class. Data hiding is also referred as Scoping and the accessibility of a method or a field of a class can be cha
9 min read
Access Modifiers in Python : Public, Private and Protected
Prerequisites: Underscore (_) in Python, Private Variables in Python Encapsulation is one of the four principles used in Object Oriented Paradigm. It is used to bind and hide data to the class. Data hiding is also referred as Scoping and the accessibility of a method or a field of a class can be cha
9 min read
Private Variables in Python
Prerequisite: Underscore in PythonIn Python, there is no existence of âPrivateâ instance variables that cannot be accessed except inside an object. However, a convention is being followed by most Python code and coders i.e., a name prefixed with an underscore, For e.g. _geek should be treated as a n
3 min read
Private Methods in Python
Encapsulation is one of the fundamental concepts in object-oriented programming (OOP) in Python. 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
6 min read
Protected variable in Python
Prerequisites: Underscore ( _ ) in Python A Variable is an identifier that we assign to a memory location which is used to hold values in a computer program. Variables are named locations of storage in the program. Based on access specification, variables can be public, protected and private in a cl
2 min read
Inheritance
Inheritance in Python
Inheritance is a fundamental concept in object-oriented programming (OOP) that allows a class (called a child or derived class) to inherit attributes and methods from another class (called a parent or base class). This promotes code reuse, modularity, and a hierarchical class structure. In this arti
7 min read
Method Overriding in Python
Method overriding is an ability of any object-oriented programming language that allows a subclass or child class to provide a specific implementation of a method that is already provided by one of its super-classes or parent classes. When a method in a subclass has the same name, the same parameter
7 min read
Operator Overloading in Python
Operator Overloading means giving extended meaning beyond their predefined operational meaning. For example operator + is used to add two integers as well as join two strings and merge two lists. It is achievable because '+' operator is overloaded by int class and str class. You might have noticed t
9 min read
Python super()
In Python, the super() function is used to refer to the parent class or superclass. It allows you to call methods defined in the superclass from the subclass, enabling you to extend and customize the functionality inherited from the parent class. Syntax of super() in PythonSyntax: super() Return : R
8 min read
Multiple Inheritance in Python
Inheritance is the mechanism to achieve the re-usability of code as one class(child class) can derive the properties of another class(parent class). It also provides transitivity ie. if class C inherits from P then all the sub-classes of C would also inherit from P. Multiple Inheritance When a class
5 min read
What Is Hybrid Inheritance In Python?
Inheritance is a fundamental concept in object-oriented programming (OOP) where a class can inherit attributes and methods from another class. Hybrid inheritance is a combination of more than one type of inheritance. In this article, we will learn about hybrid inheritance in Python. Hybrid Inheritan
3 min read
Multilevel Inheritance in Python
Python is one of the most popular and widely used Programming Languages. Python is an Object Oriented Programming language which means it has features like Inheritance, Encapsulation, Polymorphism, and Abstraction. In this article, we are going to learn about Multilevel Inheritance in Python. Pre-Re
3 min read
Multilevel Inheritance in Python
Python is one of the most popular and widely used Programming Languages. Python is an Object Oriented Programming language which means it has features like Inheritance, Encapsulation, Polymorphism, and Abstraction. In this article, we are going to learn about Multilevel Inheritance in Python. Pre-Re
3 min read
Special Methods and Testing