Python OOPS Interview question
Last Updated :
18 Dec, 2024
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
Pandas Interview Questions
Panda is a FOSS (Free and Open Source Software) Python library which provides high-performance data manipulation, in Python. It is used in various areas like data science and machine learning. Pandas is not just a library, it's an essential skill for professionals in various domains, including finan
15+ min read
Python Interview Questions and Answers
Python 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
Top 30 Python Dictionary Interview Questions
Python dictionaries are important data structures used to store key-value pairs. In this article, we will explore the Top 30 Python Dictionary interview questions to help you prepare for technical interviews.Table of ContentBasic Python Dictionary Interview QuestionsIntermediate Python Dictionary In
7 min read
Top 50 + Python Interview Questions for Data Science
Python is a popular programming language for Data Science, whether you are preparing for an interview for a data science role or looking to brush up on Python concepts. 50 + Data Science Interview QuestionIn this article, we will cover various Top Python Interview questions for Data Science that wil
15+ min read
Python Version History
Python, one of the most popular programming languages today, has a rich history of development and evolution. From its inception in the late 1980s to its current status as a versatile and powerful language, Python's version history reflects the language's adaptability and the community's dedication
5 min read
Python A-Z Quick Notes
Python is a general-purpose, high-level, interpreted programming language that supports multiple programming paradigms, including procedural, object-oriented, and functional programming, and is widely used among the developersâ community. Python was mainly developed for emphasis on code readability,
15+ min read
Scope of Python in India
In todayâs time, python is the most popular language among development professionals which was developed by Guido Van Rossum in 1991. Python is an open-source and high-level programming language that supports much functionality that makes it so popular among developers. Programming in Python is much
9 min read
5 Reasons Why Python is Good for Beginners
New beginnings are always exciting, be it starting college, joining a new sports team, selecting your first bike, or learning a new skill. But new beginnings can make us anxious, especially when these are related to our careers. Add to it the inexperience. A similar case can be made when someone dec
6 min read
Must Know Things to Clear Your Python Coding Interview
Python is not only one of the most loved languages but rather it is used in various different domains. Due to its high dependency and usage in a lot of fields, there has suddenly been an increase in the job openings in Python programming language and related frameworks. Python developers are in high
6 min read
Python Projects - Beginner to Advanced
Python is one of the most popular programming languages due to its simplicity, versatility, and supportive community. Whether youâre a beginner eager to learn the basics or an experienced programmer looking to challenge your skills, there are countless Python projects to help you grow.Hereâs a list
10 min read