Python OOPS Interview question
Last Updated :
23 Jul, 2025
In Python, Object-Oriented Programming (OOP) allows developers to structure their code in a more efficient, scalable, and maintainable way by using classes and objects. These objects can have attributes (data) and methods (functions) that represent both the state and behaviour of an entity. Python OOP provides a powerful approach to managing complex systems and applications.
In this article, we will explore common Object-Oriented Programming(OOP) interview questions related to Python. Let’s explore some key OOP interview questions that will help you master Python’s OOP features.
Basic OOPS Interview Questions
1. What is Object-Oriented Programming (OOP)?
Object-Oriented Programming (OOP) is a fundamental paradigm in Python which is designed to model real-world entities through classes and objects. It offers features like encapsulation, inheritance, polymorphism, and abstraction enabling developers to write reusable, modular, and maintainable code.
2. What are the key features of OOP?
The key features of oop are:
- Encapsulation: Bundles data and methods within a class, hiding internal details from outside access.
- Abstraction: Hides complex implementation details and exposes only necessary functionality.
- Inheritance: Allows a new class to inherit properties and methods from an existing class.
- Polymorphism: Enables a single interface to represent different behaviors.
3. What is a class and an object in Python?
- Class: A blueprint for creating objects, defining their properties and methods.
- Object: An instance of a class.
Example:
Python
class Dog:
def __init__(self, name, breed):
self.name = name
self.breed = breed
def speak(self):
print(f"{self.name} says Woof!")
dog1 = Dog("Buddy", "Golden Retriever")
dog1.speak()
4. What is the difference between a class and an instance?
- Class: Defines the structure and behavior (attributes and methods).
- Instance: A concrete occurrence of a class with actual data
5. What is the __init__
method in Python?
The __init__
method is a constructor used to initialize an object’s attributes when it is created and it is also known as constructor. The __init__ method is part of Python's object-oriented programming (OOP) mechanism and is used to set up the initial state of the object when it is instantiated.
Example:
Python
class Person:
def __init__(self, name):
self.name = name
p = Person("Alice")
6. What is self
in Python classes?
self
is a reference to the current instance of the class. It is used to access attributes and methods of the class. When you define a method inside a class, the first parameter of the method is always self, which allows the method to refer to the object (or instance) on which the method was called.
7. What is the difference between instance variables and class variables?
- Instance variables: Instance variables unique to each object.
- Class variables: Shared among all objects of a class.
Example:
Python
class Demo:
class_var = "shared" # class variable
def __init__(self, val):
self.instance_var = val # instance variable
8. What is inheritance in Python?
Inheritance allows a class to inherit attributes and methods from another class. Inheritance enables the child class to inherit the properties (attributes) and behaviors (methods) of the parent class, and it can also define its own additional attributes and methods or override existing ones.
Example:
Python
# Define the Parent class (base class)
class Parent:
pass
# Define the Child class that inherits from Parent class
class Child(Parent):
pass
9. What is method overloading in Python?
Method overloading in Python refers to the ability to define multiple methods with the same name but with different parameters (different numbers or types of arguments).
Example:
Python
def greet(name="Guest"):
# Print a greeting message, using the 'name' argument.
print(f"Hello, {name}")
10. What is method overriding in Python?
Method overriding allows a subclass to provide a specific implementation of a method that is already defined in its superclass. This means that the subclass can "override" the behavior of the method inherited from the parent class, providing a different version that is more suitable for the subclass.
Example:
Python
class Parent:
def show(self):
print("Parent")
class Child(Parent):
def show(self): # Method overriding
print("Child")
11. What is polymorphism in Python?
Polymorphism allows objects to be treated as instances of their parent class, enabling different implementations for the same interface. It enables a single function, method, or operator to work with different types of objects in a way that is determined at runtime, allowing code to be more flexible and reusable.
Example:
Python
class Bird:
# Method to make a sound for the Bird class
def speak(self):
print("Chirp")
class Dog:
# Method to make a sound for the Dog class
def speak(self):
print("Bark")
12. What is encapsulation, and how does Python achieve it?
Encapsulation is one of the fundamental principles of OOP. It allows the internal representation of an object to be hidden from the outside world and exposes only what is necessary through a controlled interface.
Example:
Python
class Example:
def __init__(self):
self.__private_var = 42
13. What is the super()
function in Python?
super()
allows access to methods of the parent class and it’s often used to call the parent class’s constructor.
Example:
Python
class A:
def method(self):
print("Method in class A")
class B(A):
def method(self):
super().method() # Call method from class A
print("Method in class B")
class C(A):
def method(self):
super().method() # Call method from class A
print("Method in class C")
14. What are abstract classes in Python?
Abstract class is a class that serves as a blueprint for other classes. It defines a structure that derived classes must follow but does not provide full implementation, abstract classes cannot be instantiated directly which means they are meant to be subclassed.
Example:
Python
from abc import ABC, abstractmethod
class Animal(ABC):
@abstractmethod
def sound(self):
pass
15. What is the difference between is
and ==
?
'is' checks if two objects are the same instance(identity) and '==' checks if the two objects have the same value(equality).
16. What is multiple inheritance in Python?
Multiple inheritance allows a subclass to inherit features from multiple parent classes, making it more versatile and capable of combining behaviors from different sources.
Python
class ChildClass(ParentClass1, ParentClass2, ...):
# Class body
17. What is the diamond problem in multiple inheritance? How does Python handle it?
The Diamond Problem in multiple inheritance is a classic issue that arises when a class inherits from two classes that both inherit from a common ancestor. The problem occurs because, in such a scenario, it's unclear which version of the inherited method should be invoked when the method is called on the subclass.
18. What are class methods in Python?
Class methods are defined with the @classmethod
decorator and take 'cls'
(class reference) as their first argument.
Python
class Demo:
@classmethod
def info(cls):
print("Class Method")
19. What is the difference between staticmethod
and classmethod
?
In Python, both @staticmethod and @classmethod @staticmethod
and @classmethod
are used to define methods that are not bound to the instance of the class (i.e., they can be called on the class itself).
Aspect | staticmethod | classmethod
|
---|
Binding | Not bound to either the instance or the class. | Bound to the class, not the instance. |
First Argument | Does not take self or cls as the first argument. | Takes cls as the first argument (refers to the class). |
Access to Class/Instance Variables | Cannot access or modify instance or class variables. | Can access and modify class variables (but not instance variables). |
Call | Can be called on the class or an instance. | Can be called on the class or an instance. |
20. What are magic methods in Python?
Magic methods(dunder methods) start and end with double underscores providing operator overloading and custom behaviors.
Examples: __str__
, __len__ and
, __init__ so on...
Advanced Python Interview OOPs Questions
21. How does Python handle garbage collection?
Python uses automatic garbage collection to manage memory by identifying and removing unused objects and It employs reference counting and a cyclic garbage collector.
A metaclass is a class of a class that defines how classes behave and classes are instances of metaclasses. Essentially, metaclasses define the "rules" for building classes, much like a class defines the rules for creating objects.
Example:
Python
class Meta(type):
# This is an empty metaclass that inherits from 'type'
pass
class Demo(metaclass=Meta):
# The 'metaclass=Meta' instructs Python to use the 'Meta' metaclass
pass
23. How is data hiding implemented in Python?
Data hiding is implemented using private attributes (__attribute) and even though it is not completely hidden, it is still difficult to access without name mangling.
24.What is the purpose of __slots__ in Python classes?
__slots__ attribute limits the attributes that can be added to an instance improving memory usage.
Example:
Python
class Example:
__slots__ = ['name', 'age']
25. What is the Global Interpreter Lock (GIL) and its impact on Python OOP?
The GIL ensures only one thread executes Python bytecode at a time affecting multithreaded programs. Its purpose is to prevent multiple native threads from executing Python bytecode at the same time, ensuring thread safety in Python's memory management system. .
26.How do you achieve operator overloading in Python?
Operator overloading is achieved using magic methods like __add__ and __eq__.
Example:
Python
class Point:
def __add__(self, other):
return Point(self.x + other.x)
26. What is the difference between shallow copy and deep copy in Python?
In Python, shallow copy and deep copy are used to create copies of objects. They differ in how they handle nested objects, such as lists within lists or objects containing other objects. A shallow copy creates a new object but does not copy the nested objects inside it and A deep copy creates a new object and recursively copies all objects within it, including nested objects.
27. What is the difference between composition and inheritance?
Composition and inheritance are two fundamental object-oriented programming (OOP) techniques for creating relationships between classes. The main difference between inheritance and composition is that:
- Inheritance: "Is-a" relationship (e.g., a Car is-a Vehicle).
- Composition: "Has-a" relationship (e.g., a Car has-a Engine).
28. How do you implement design patterns like Singleton in Python?
Singleton ensures only one instance of a class exists. it design pattern ensures that a class has only one instance and provides a global point of access to it.
Example:
Python
class Singleton:
_instance = None
def __new__(cls, *args, **kwargs):
if not cls._instance:
cls._instance = super().__new__(cls)
return cls._instance
29. Explain Python’s MRO with an example.
Python's , determines the order in which classes are searched when calling a method or accessing an attribute. It is crucial in object-oriented programming, especially when dealing with multiple inheritance.
Example:
Python
class A:
# Class A is a base class with no methods or attributes
pass
class B(A):
# Class B inherits from A
pass
class C(A):
# Class C also inherits from A
pass
class D(B, C):
# Class D inherits from both B and C
pass
print(D.mro())
30. How would you identify the MRO of a class programmatically?
We can identify the Method Resolution Order (MRO) of a class programmatically in Python using the mro() Method or by using the __mro__ attribute.
- Using the
mro()
method: This method returns a list of classes in the order they are checked for method resolution. - Using the
__mro__
attribute: This attribute directly provides the MRO as a tuple of classes.
Similar Reads
Python Tutorial - Learn Python Programming Language Python is one of the most popular programming languages. Itâs simple to use, packed with features and supported by a wide range of libraries and frameworks. Its clean syntax makes it beginner-friendly. It'sA high-level language, used in web development, data science, automation, AI and more.Known fo
7 min read
Python Fundamentals
Python IntroductionPython was created by Guido van Rossum in 1991 and further developed by the Python Software Foundation. It was designed with focus on code readability and its syntax allows us to express concepts in fewer lines of code.Key Features of PythonPythonâs simple and readable syntax makes it beginner-frien
3 min read
Input and Output in PythonUnderstanding input and output operations is fundamental to Python programming. With the print() function, we can display output in various formats, while the input() function enables interaction with users by gathering input during program execution. Taking input in PythonPython's input() function
7 min read
Python VariablesIn Python, variables are used to store data that can be referenced and manipulated during program execution. A variable is essentially a name that is assigned to a value. Unlike many other programming languages, Python variables do not require explicit declaration of type. The type of the variable i
6 min read
Python OperatorsIn Python programming, Operators in general are used to perform operations on values and variables. These are standard symbols used for logical and arithmetic operations. In this article, we will look into different types of Python operators. OPERATORS: These are the special symbols. Eg- + , * , /,
6 min read
Python KeywordsKeywords in Python are reserved words that have special meanings and serve specific purposes in the language syntax. Python keywords cannot be used as the names of variables, functions, and classes or any other identifier. Getting List of all Python keywordsWe can also get all the keyword names usin
2 min read
Python Data TypesPython Data types are the classification or categorization of data items. It represents the kind of value that tells what operations can be performed on a particular data. Since everything is an object in Python programming, Python data types are classes and variables are instances (objects) of thes
9 min read
Conditional Statements in PythonConditional statements in Python are used to execute certain blocks of code based on specific conditions. These statements help control the flow of a program, making it behave differently in different situations.If Conditional Statement in PythonIf statement is the simplest form of a conditional sta
6 min read
Loops in Python - For, While and Nested LoopsLoops in Python are used to repeat actions efficiently. The main types are For loops (counting through items) and While loops (based on conditions). In this article, we will look at Python loops and understand their working with the help of examples. For Loop in PythonFor loops is used to iterate ov
9 min read
Python FunctionsPython Functions is a block of statements that does a specific task. The idea is to put some commonly or repeatedly done task together and make a function so that instead of writing the same code again and again for different inputs, we can do the function calls to reuse code contained in it over an
9 min read
Recursion in PythonRecursion involves a function calling itself directly or indirectly to solve a problem by breaking it down into simpler and more manageable parts. In Python, recursion is widely used for tasks that can be divided into identical subtasks.In Python, a recursive function is defined like any other funct
6 min read
Python Lambda FunctionsPython Lambda Functions are anonymous functions means that the function is without a name. As we already know the def keyword is used to define a normal function in Python. Similarly, the lambda keyword is used to define an anonymous function in Python. In the example, we defined a lambda function(u
6 min read
Python Data Structures
Python StringA string is a sequence of characters. Python treats anything inside quotes as a string. This includes letters, numbers, and symbols. Python has no character data type so single character is a string of length 1.Pythons = "GfG" print(s[1]) # access 2nd char s1 = s + s[0] # update print(s1) # printOut
6 min read
Python ListsIn Python, a list is a built-in dynamic sized array (automatically grows and shrinks). We can store all types of items (including another list) in a list. A list may contain mixed type of items, this is possible because a list mainly stores references at contiguous locations and actual items maybe s
6 min read
Python TuplesA tuple in Python is an immutable ordered collection of elements. Tuples are similar to lists, but unlike lists, they cannot be changed after their creation (i.e., they are immutable). Tuples can hold elements of different data types. The main characteristics of tuples are being ordered , heterogene
6 min read
Dictionaries in PythonPython dictionary is a data structure that stores the value in key: value pairs. Values in a dictionary can be of any data type and can be duplicated, whereas keys can't be repeated and must be immutable. Example: Here, The data is stored in key:value pairs in dictionaries, which makes it easier to
7 min read
Python SetsPython set is an unordered collection of multiple items having different datatypes. In Python, sets are mutable, unindexed and do not contain duplicates. The order of elements in a set is not preserved and can change.Creating a Set in PythonIn Python, the most basic and efficient method for creating
10 min read
Python ArraysLists in Python are the most flexible and commonly used data structure for sequential storage. They are similar to arrays in other languages but with several key differences:Dynamic Typing: Python lists can hold elements of different types in the same list. We can have an integer, a string and even
9 min read
List Comprehension in PythonList comprehension is a way to create lists using a concise syntax. It allows us to generate a new list by applying an expression to each item in an existing iterable (such as a list or range). This helps us to write cleaner, more readable code compared to traditional looping techniques.For example,
4 min read
Advanced Python
Python OOP ConceptsObject Oriented Programming is a fundamental concept in Python, empowering developers to build modular, maintainable, and scalable applications. 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 th
11 min read
Python Exception HandlingPython Exception Handling handles errors that occur during the execution of a program. Exception handling allows to respond to the error, instead of crashing the running program. It enables you to catch and manage errors, making your code more robust and user-friendly. Let's look at an example:Handl
6 min read
File Handling in PythonFile handling refers to the process of performing operations on a file, such as creating, opening, reading, writing and closing it through a programming interface. It involves managing the data flow between the program and the file system on the storage device, ensuring that data is handled safely a
4 min read
Python Database TutorialPython being a high-level language provides support for various databases. We can connect and run queries for a particular database using Python and without writing raw queries in the terminal or shell of that particular database, we just need to have that database installed in our system.A database
4 min read
Python MongoDB TutorialMongoDB is a popular NoSQL database designed to store and manage data flexibly and at scale. Unlike traditional relational databases that use tables and rows, MongoDB stores data as JSON-like documents using a format called BSON (Binary JSON). This document-oriented model makes it easy to handle com
2 min read
Python MySQLMySQL is a widely used open-source relational database for managing structured data. Integrating it with Python enables efficient data storage, retrieval and manipulation within applications. To work with MySQL in Python, we use MySQL Connector, a driver that enables seamless integration between the
9 min read
Python PackagesPython packages are a way to organize and structure code by grouping related modules into directories. A package is essentially a folder that contains an __init__.py file and one or more Python files (modules). This organization helps manage and reuse code effectively, especially in larger projects.
12 min read
Python ModulesPython Module is a file that contains built-in functions, classes,its and variables. There are many Python modules, each with its specific work.In this article, we will cover all about Python modules, such as How to create our own simple module, Import Python modules, From statements in Python, we c
7 min read
Python DSA LibrariesData Structures and Algorithms (DSA) serve as the backbone for efficient problem-solving and software development. Python, known for its simplicity and versatility, offers a plethora of libraries and packages that facilitate the implementation of various DSA concepts. In this article, we'll delve in
15 min read
List of Python GUI Library and PackagesGraphical User Interfaces (GUIs) play a pivotal role in enhancing user interaction and experience. Python, known for its simplicity and versatility, has evolved into a prominent choice for building GUI applications. With the advent of Python 3, developers have been equipped with lots of tools and li
11 min read
Data Science with Python
NumPy Tutorial - Python LibraryNumPy is a core Python library for numerical computing, built for handling large arrays and matrices efficiently.ndarray object â Stores homogeneous data in n-dimensional arrays for fast processing.Vectorized operations â Perform element-wise calculations without explicit loops.Broadcasting â Apply
3 min read
Pandas TutorialPandas (stands for Python Data Analysis) is an open-source software library designed for data manipulation and analysis. Revolves around two primary Data structures: Series (1D) and DataFrame (2D)Built on top of NumPy, efficiently manages large datasets, offering tools for data cleaning, transformat
6 min read
Matplotlib TutorialMatplotlib is an open-source visualization library for the Python programming language, widely used for creating static, animated and interactive plots. It provides an object-oriented API for embedding plots into applications using general-purpose GUI toolkits like Tkinter, Qt, GTK and wxPython. It
5 min read
Python Seaborn TutorialSeaborn is a library mostly used for statistical plotting in Python. It is built on top of Matplotlib and provides beautiful default styles and color palettes to make statistical plots more attractive.In this tutorial, we will learn about Python Seaborn from basics to advance using a huge dataset of
15+ min read
StatsModel Library- TutorialStatsmodels is a useful Python library for doing statistics and hypothesis testing. It provides tools for fitting various statistical models, performing tests and analyzing data. It is especially used for tasks in data science ,economics and other fields where understanding data is important. It is
4 min read
Learning Model Building in Scikit-learnBuilding machine learning models from scratch can be complex and time-consuming. Scikit-learn which is an open-source Python library which helps in making machine learning more accessible. It provides a straightforward, consistent interface for a variety of tasks like classification, regression, clu
8 min read
TensorFlow TutorialTensorFlow is an open-source machine-learning framework developed by Google. It is written in Python, making it accessible and easy to understand. It is designed to build and train machine learning (ML) and deep learning models. It is highly scalable for both research and production.It supports CPUs
2 min read
PyTorch TutorialPyTorch is an open-source deep learning framework designed to simplify the process of building neural networks and machine learning models. With its dynamic computation graph, PyTorch allows developers to modify the networkâs behavior in real-time, making it an excellent choice for both beginners an
7 min read
Web Development with Python
Flask TutorialFlask is a lightweight and powerful web framework for Python. Itâs often called a "micro-framework" because it provides the essentials for web development without unnecessary complexity. Unlike Django, which comes with built-in features like authentication and an admin panel, Flask keeps things mini
8 min read
Django Tutorial | Learn Django FrameworkDjango is a Python framework that simplifies web development by handling complex tasks for you. It follows the "Don't Repeat Yourself" (DRY) principle, promoting reusable components and making development faster. With built-in features like user authentication, database connections, and CRUD operati
10 min read
Django ORM - Inserting, Updating & Deleting DataDjango's Object-Relational Mapping (ORM) is one of the key features that simplifies interaction with the database. It allows developers to define their database schema in Python classes and manage data without writing raw SQL queries. The Django ORM bridges the gap between Python objects and databas
4 min read
Templating With Jinja2 in FlaskFlask is a lightweight WSGI framework that is built on Python programming. WSGI simply means Web Server Gateway Interface. Flask is widely used as a backend to develop a fully-fledged Website. And to make a sure website, templating is very important. Flask is supported by inbuilt template support na
6 min read
Django TemplatesTemplates are the third and most important part of Django's MVT Structure. A Django template is basically an HTML file that can also include CSS and JavaScript. The Django framework uses these templates to dynamically generate web pages that users interact with. Since Django primarily handles the ba
7 min read
Python | Build a REST API using FlaskPrerequisite: Introduction to Rest API REST stands for REpresentational State Transfer and is an architectural style used in modern web development. It defines a set or rules/constraints for a web application to send and receive data. In this article, we will build a REST API in Python using the Fla
3 min read
How to Create a basic API using Django Rest Framework ?Django REST Framework (DRF) is a powerful extension of Django that helps you build APIs quickly and easily. It simplifies exposing your Django models as RESTfulAPIs, which can be consumed by frontend apps, mobile clients or other services.Before creating an API, there are three main steps to underst
4 min read
Python Practice
Python QuizThese Python quiz questions are designed to help you become more familiar with Python and test your knowledge across various topics. From Python basics to advanced concepts, these topic-specific quizzes offer a comprehensive way to practice and assess your understanding of Python concepts. These Pyt
3 min read
Python Coding Practice ProblemsThis collection of Python coding practice problems is designed to help you improve your overall programming skills in Python.The links below lead to different topic pages, each containing coding problems, and this page also includes links to quizzes. You need to log in first to write your code. Your
1 min read
Python Interview Questions and AnswersPython is the most used language in top companies such as Intel, IBM, NASA, Pixar, Netflix, Facebook, JP Morgan Chase, Spotify and many more because of its simplicity and powerful libraries. To crack their Online Assessment and Interview Rounds as a Python developer, we need to master important Pyth
15+ min read