Are you someone who is going for a Python interview and want to know some of the python OOPs concept that could be asked in the interview?
You are at the right place!!
OOP or Object-Oriented Programming is one of the mostly used programming paradigms/styles of writing reusable, easy to understand and use and, secure code.
Many interviewers ask questions related to OOP as this is a general concept in many programming languages and is used in software development a lot. So, it is important for the interviewer to know that you are good at it before hiring.
In this blog I am going to explain the interview question answers with code examples to make it clearer and more useful for your interview.
So… stick till the end!

What Will You Learn?
- 1 Python OOPs Questions
- 2 What is object in Python
- 3 What is class in Python
- 4 What is encapsulation in Python
- 5 What is abstraction in Python
- 6 What is inheritance in Python
- 7 What is polymorphism in Python
- 8 How do you create a constructor in Python
- 9 What is operator overloading in Python
- 10 What are magic methods in Python class
- 11 What is a static method
- 12 What is the purpose of self in Python
- 13 What is the use of super() function
- 14 How does Python handle private and protected members in class
- 15 Can you explain duck typing in Python
- 16 Conclusion
Python OOPs Questions
Some of the mostly asked OOP’s questions in Python are the following –
- What is object in Python?
- What is class in Python?
- What is encapsulation in Python? Give an example.
- What is abstraction in Python? How would you implement it?
- What is inheritance in Python? Give an example.
- What is polymorphism in Python? Give an example.
- How do you create a constructor in Python?
- What is operator overloading in Python?
- What are magic methods in Python class?
- What is a static method and how it is different from normal method in Python?
- What is the purpose of “self” keyword in Python?
- What is the use of super() function?
- How does Python handle private and protected members in class?
- Can you explain duck typing in Python?
Let’s dive into each question in-depth and discuss their solution with code examples.
What is object in Python
An object is an instance of a class. When a class is defined, no memory is allocated until an object is created. An object holds the attributes defined by the class.
Object can be considered a kind of variable that takes memory but unlike simple variables that could be either int/str/float/list/tuple/dictionary type, object could have any custom type like Animal/Car/Machine etc.
# Python object
marcedes = Car("Toyota", "Corolla")
What is class in Python
Class is a blueprint of how an object should have or can do. If we are creating a class for Car
then it is like thinking of how the actual car my_car
will have and can do.
Creating a class does not take memory, if you create an object of that class only it will take the memory.
class Car:
def __init__(self, make, model):
self._make = make
self._model = model
What is encapsulation in Python
Encapsulation refers to the bundling of data (attributes) and methods (functions) that operate on the data into a single unit or class. With encapsulation, the class makes sure that nobody outside of that class can access that data/method directly.
It helps in hiding the internal state of an object and only exposing the necessary methods to interact with the object’s state.
class Car:
def __init__(self, make, model):
self._make = make # Encapsulated attribute
self._model = model # Encapsulated attribute
def get_make(self): # Getter method
return self._make
def get_model(self): # Getter method
return self._model
def set_make(self, make): # Setter method
self._make = make
def set_model(self, model): # Setter method
self._model = model
my_car = Car("Toyota", "Corolla")
print(my_car.get_make()) # Output: Toyota
my_car.set_make("Honda")
print(my_car.get_make()) # Output: Honda
What is abstraction in Python
Abstraction refers to the process of hiding the complex implementation details and showing only the essential features of the object.
If you want a car then as an end user you only need to know about some outer details and not about all intricate and complicated stuff like how the engine works, how headlines get turned on etc.
It allows for building models that represent real-world entities and interactions, focusing on what an object does rather than how it does it.
from abc import ABC, abstractmethod
class Shape(ABC): # Abstract class
@abstractmethod
def area(self):
pass
class Circle(Shape):
def __init__(self, radius):
self.radius = radius
def area(self):
return 3.14 * self.radius ** 2
class Rectangle(Shape):
def __init__(self, length, width):
self.length = length
self.width = width
def area(self):
return self.length * self.width
circle = Circle(5)
print(circle.area()) # Output: 78.5
rectangle = Rectangle(4, 6)
print(rectangle.area()) # Output: 24
What is inheritance in Python
Inheritance allows a class (subclass or derived class) to inherit attributes and methods from another class (superclass or base class), promoting code reuse and creating a hierarchy of classes with shared characteristics.
It enables the creation of specialized subclasses that extend or override the behavior of the superclass, facilitating modular and maintainable code.
class Animal:
def __init__(self, species):
self.species = species
def sound(self):
pass
class Dog(Animal):
def sound(self):
return "Woof!"
class Cat(Animal):
def sound(self):
return "Meow!"
dog = Dog("Canine")
print(dog.sound()) # Output: Woof!
cat = Cat("Feline")
print(cat.sound()) # Output: Meow!
What is polymorphism in Python
Polymorphism refers to the ability of objects to take on multiple forms or behaviours depending on their context or the type of data they operate on.
It allows for the same method name to behave differently in different contexts or for different types of objects, promoting flexibility and extensibility.
class Animal:
def sound(self):
return "Animal sound"
class Dog(Animal):
def sound(self):
return "Woof!"
class Cat(Animal):
def sound(self):
return "Meow!"
def make_sound(animal):
return animal.sound()
animal = Animal()
print(make_sound(animal)) # Output: Animal sound
dog = Dog()
print(make_sound(dog)) # Output: Woof!
cat = Cat()
print(make_sound(cat)) # Output: Meow!
How do you create a constructor in Python
In Python, a constructor is a special method called __init__() that is automatically invoked when a new object of a class is created. It is used to initialize the object’s state or set up initial values for its attributes.
class Car:
def __init__(self, make, model, year):
self.make = make
self.model = model
self.year = year
car1 = Car("Toyota", "Corolla", 2020)
print(car1.make) # Output: Toyota
print(car1.model) # Output: Corolla
print(car1.year) # Output: 2020
What is operator overloading in Python
Operator overloading in Python refers to the ability to define custom behaviour for built-in operators (+, -, *, /, etc.) when they are used with user-defined objects.
By implementing special methods (also known as magic methods or dunder methods) with predefined names, such as __add__() for addition, __sub__() for subtraction, and so on, in a class, developers can customize how instances of that class behave when operated upon with the corresponding operators.
class Complex:
def __init__(self, real, img):
self.real = real
self.img = img
def __add__(self, c):
return Complex(self.real+c.real, self.img+c.img)
def __sub__(self, c):
return Complex(self.real-c.real, self.img-c.img)
def __str__(self):
return f"{self.real} + {self.img}i"
c1 = Complex(1, 2)
c2 = Complex(2, 3)
print(c1+c2) # 3 + 5i
print(c1-c2) # -1 + -1i
What are magic methods in Python class
Magic methods in Python are special methods surrounded by double underscores, used to customize the behaviour of classes and objects. They are invoked implicitly by the interpreter in response to specific operations or built-in functions.
Examples include `__init__()` for object initialization and `__str__()` for string representation. They enable developers to define how instances of a class behave in various contexts, such as arithmetic operations, iteration, comparison, and more.
class Complex:
def __init__(self, real, img):
self.real = real
self.img = img
def __abs__(self):
real = abs(self.real)
img = abs(self.img)
return Complex(real, img)
def __str__(self):
return f"{self.real} + {self.img}i"
c = Complex(-1, -2)
print(abs(c)) # 1 + 2i
What is a static method
Static methods are methods that do not operate on either instances or classes and are independent of the class state.
They are defined using the @staticmethod decorator and do not require the self or cls parameters, making them similar to regular functions but within the class namespace.
class MathOperations:
@staticmethod
def add(x, y):
return x + y
@staticmethod
def subtract(x, y):
return x - y
print(MathOperations.add(5, 3)) # Output: 8
print(MathOperations.subtract(5, 3)) # Output: 2
What is the purpose of self
in Python
`self` is the reference the object uses to refer to itself. Whenever you want to attach something on the object or call method on that object inside the class, you can use `self` keyword to call that method.
class Dog:
def __init__(self, name, age):
self.name = name
self.age = age
def bark(self):
print(f"{self.name} says woof!")
my_dog = Dog("Buddy", 3)
my_dog.bark() # Buddy says woof!
What is the use of super()
function
The super() function in Python is used to call methods and access attributes from the superclass (parent class) within a subclass (child class).
It allows subclasses to inherit and leverage behaviour from their superclass, facilitating code reuse and maintaining a clean and organized class hierarchy.
By using super(), developers can invoke superclass methods and constructors, ensuring that all necessary initialization and functionality from the superclass are properly executed within the subclass.
class Emp():
def __init__(self, id, name, Add):
self.id = id
self.name = name
self.Add = Add
# Class freelancer inherits EMP
class Freelance(Emp):
def __init__(self, id, name, Add, Emails):
super().__init__(id, name, Add)
self.Emails = Emails
Emp_1 = Freelance(103, "Suraj kr gupta", "Noida" , "KKK@gmails")
print('The ID is:', Emp_1.id) # The ID is: 103
print('The Name is:', Emp_1.name) # The Name is: Suraj kr gupta
print('The Address is:', Emp_1.Add) # The Address is: Noida
print('The Emails is:', Emp_1.Emails) # The Emails is: KKK@gmails
How does Python handle private and protected members in class
Python does not have strict private or protected members like other languages. However, conventionally:
Protected members are indicated by a single underscore (_). These can still be accessed outside the class but are intended for internal use.
Private members are indicated by double underscores (__), which triggers name mangling, making it harder (but not impossible) to access from outside the class.
class Student:
# Private
__id = None
# Protected
_roll = None
# constructor
def __init__(self, id, roll):
self.__id = id
self._roll = roll
# protected member function
def _displayRollAndBranch(self):
# accessing protected data members
print("ID:", self.__id)
print("Roll:", self._roll)
# derived class
class Geek(Student):
# constructor
def __init__(self, id, roll):
Student.__init__(self, id, roll)
# public member function
def displayDetails(self):
# accessing protected data members of super class
print("Name:", self._name)
# accessing protected member functions of super class
self._displayRollAndBranch()
stu = Student(1234567, 10)
print(stu._roll) # Still can be accessed
print(stu.__id) # error
Can you explain duck typing in Python
Duck Typing in Python is a concept in dynamic typing that focuses on the behavior of an object rather than its actual type. The name comes from the phrase:
“If it looks like a duck, swims like a duck, and quacks like a duck, then it probably is a duck.”
class Duck:
def quack(self):
return "Quack!"
class Person:
def quack(self):
return "I'm quacking like a duck!"
def make_it_quack(entity):
# We don't care about the type of 'entity'.
# We only care if it has the method `quack`.
print(entity.quack())
donald = Duck()
john = Person()
make_it_quack(donald) # Output: Quack!
make_it_quack(john) # Output: I'm quacking like a duck!
Conclusion
With this, I trust you have solidified some key concepts in Python related to OOPs and are well-prepared for your interview. However, it’s essential to practice so that the knowledge you’ve just reviewed stays fresh in your mind and you can perform really well on each question.
Instead of memorizing the exact questions, it will be better if you can understand the concepts in more depth and give explanations on your own.
Liked this blog and want to read more similar blogs? Go to the next blog and start reading😉.
If you need some more explanations, refer to the following links.
References:
- https://medium.com/@edwinvarghese4442/top-oops-questions-asked-in-python-interviews-8bd01623e6f5
- https://www.hirist.tech/blog/top-25-python-oops-interview-question-2024/
- https://www.geeksforgeeks.org/python-super/
- https://www.geeksforgeeks.org/access-modifiers-in-python-public-private-and-protected/