This detailed guide addresses Object-Oriented Programming interview questions specifically in Python, designed to assist you in your preparation for technical interviews.
Basic OOP Concepts
1. What is Object-Oriented Programming?
Object-Oriented Programming (OOP) is a programming paradigm that structures code into objects, each comprising data (also known as attributes) and functions (referred to as methods). This paradigm highlights the importance of modularity and promotes the reuse of code across different applications.
Four main principles of OOP:
- Encapsulation
- Inheritance
- Polymorphism
- Abstraction
### 1. What is a class in Python?What is a class in Python?
A class serves as a template for generating objects. It specifies the characteristics and functions that the objects will possess.
Example:
class Car:
def __init__(self, brand, model):
self.brand = brand
self.model = model
def display_info(self):
print(f"{self.brand} {self.model}")
my_car = Car("Toyota", "Camry")
my_car.display_info()
Output:
Toyota Camry
1.What is an object in Python?
An object represents a specific instance of a class. It holds real values and has the capability to utilize the methods that are specified within the class.
Example:
class Dog:
def __init__(self, name):
self.name = name
dog1 = Dog("Buddy") # dog1 is an object
dog2 = Dog("Max") # dog2 is another object
1. What is the __init__ method?What is the __init__ method?
init serves as a constructor function that is invoked automatically upon the instantiation of an object. Its primary role is to set up the properties of the object.
Example:
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
print(f"{name} object created")
person = Person("Alice", 25)
Output:
Alice object created
### 1. What is self in Python?What is self in Python?
self denotes the present instance of the class. It serves the purpose of accessing the class's variables and methods.
Example:
class Counter:
def __init__(self):
self.count = 0
def increment(self):
self.count += 1
def get_count(self):
return self.count
counter = Counter()
counter.increment()
print(counter.get_count()) # 1
Encapsulation
6. What is encapsulation?
Encapsulation refers to the practice of grouping data and functions within a class while limiting direct interaction with certain elements. This is accomplished through the use of access modifiers.
Example:
class BankAccount:
def __init__(self, balance):
self.__balance = balance # private attribute
def deposit(self, amount):
if amount > 0:
self.__balance += amount
def get_balance(self):
return self.__balance
account = BankAccount(1000)
account.deposit(500)
print(account.get_balance()) # 1500
# print(account.__balance) # Error: private attribute
7. What are access modifiers in Python?
Python uses naming conventions for access control:
- Public: No underscore prefix (accessible everywhere)
- Protected: Single underscore
_variable(hint: internal use) - Private: Double underscore
__variable(name mangling applied)
Example:
class Example:
def __init__(self):
self.public = "Public"
self._protected = "Protected"
self.__private = "Private"
obj = Example()
print(obj.public) # Public
print(obj._protected) # Protected (still accessible)
# print(obj.__private) # Error
8. What is name mangling?
Name mangling in Python serves to obscure access to private attributes from external sources. Attributes designated as private, which have a prefix of _, are transformed into ClassName__attribute.
Example:
class Test:
def __init__(self):
self.__secret = "Hidden"
obj = Test()
# print(obj.__secret) # Error
print(obj._Test__secret) # Hidden (name mangling)
Inheritance
9. What is inheritance?
Inheritance enables a class to acquire properties and methods from a different class. The derived class has the capability to utilize or modify the functionalities of the base class.
Example:
class Animal:
def speak(self):
print("Animal makes sound")
class Dog(Animal):
def speak(self):
print("Dog barks")
dog = Dog()
dog.speak() # Dog barks
10. What are the types of inheritance?
1.
- Single Inheritance: A single parent with one child
- Multiple Inheritance: One child deriving from multiple parents
- Multilevel Inheritance: A sequence of inheritance levels
- Hierarchical Inheritance: One parent with several children
- Hybrid Inheritance: A mix of the aforementioned types
Example of Multiple Inheritance:
class Father:
def skills(self):
print("Gardening")
class Mother:
def skills(self):
print("Cooking")
class Child(Father, Mother):
pass
child = Child()
child.skills() # Gardening (MRO: Father first)
11. What is the super function?
The super function is utilized to invoke methods from a superclass. This functionality is frequently employed in init to set up attributes inherited from the parent class.
Example:
class Vehicle:
def __init__(self, brand):
self.brand = brand
class Car(Vehicle):
def __init__(self, brand, model):
super().__init__(brand) # call parent constructor
self.model = model
car = Car("Toyota", "Camry")
print(f"{car.brand} {car.model}")
12. What is Method Resolution Order (MRO)?
MRO refers to the sequence in which Python looks for methods within a class hierarchy. To observe it, simply utilize ClassName.mro or ClassName.mro.
Example:
class A:
pass
class B(A):
pass
class C(A):
pass
class D(B, C):
pass
print(D.mro())
Polymorphism
13. What is polymorphism?
Polymorphism is defined as "many forms". This concept enables methods to share the same name while possessing distinct implementations across various classes.
Example:
class Cat:
def sound(self):
return "Meow"
class Dog:
def sound(self):
return "Bark"
def make_sound(animal):
print(animal.sound())
cat = Cat()
dog = Dog()
make_sound(cat) # Meow
make_sound(dog) # Bark
14. What is method overriding?
Method overriding takes place when a subclass offers an alternative implementation for a method that has already been established in its superclass.
Example:
class Shape:
def area(self):
return 0
class Rectangle(Shape):
def __init__(self, width, height):
self.width = width
self.height = height
def area(self): # overriding parent method
return self.width * self.height
rect = Rectangle(5, 3)
print(rect.area()) # 15
15. What is method overloading?
Python does not provide conventional method overloading. Nonetheless, you can replicate similar functionality by utilizing default arguments or the *args feature.
Example:
class Calculator:
def add(self, a, b=0, c=0):
return a + b + c
calc = Calculator()
print(calc.add(5)) # 5
print(calc.add(5, 3)) # 8
print(calc.add(5, 3, 2)) # 10
Abstraction
16. What is abstraction?
Abstraction conceals the underlying implementation specifics while presenting solely the critical attributes. In Python, this is accomplished through the use of abstract classes and abstract methods.
Example:
from abc import ABC, abstractmethod
class Shape(ABC):
@abstractmethod
def area(self):
pass
class Circle(Shape):
def __init__(self, radius):
self.radius = radius
def area(self):
return 3.14 * self.radius ** 2
circle = Circle(5)
print(circle.area()) # 78.5
17. What is an abstract class?
An abstract class cannot be created as an instance and may include abstract methods that must be defined by derived classes.
Example:
from abc import ABC, abstractmethod
class Animal(ABC):
@abstractmethod
def sound(self):
pass
# animal = Animal() # Error: cannot instantiate
class Dog(Animal):
def sound(self):
return "Bark"
dog = Dog()
print(dog.sound()) # Bark
Special Methods (Magic Methods)
18. What are magic methods?
Magic methods (dunder methods) are special methods with double underscores that provide special functionality. Examples: init, str, len.
Example:
class Book:
def __init__(self, title, pages):
self.title = title
self.pages = pages
def __str__(self):
return f"{self.title} ({self.pages} pages)"
def __len__(self):
return self.pages
book = Book("Python Guide", 300)
print(book) # Python Guide (300 pages)
print(len(book)) # 300
19. What is the difference between __str__ and __repr__?
-
str: Human-readable string representation (used byprint) -
repr: Official string representation (used by debugger)
Example:
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
def __str__(self):
return f"Point at ({self.x}, {self.y})"
def __repr__(self):
return f"Point({self.x}, {self.y})"
p = Point(3, 4)
print(p) # Point at (3, 4)
print(repr(p)) # Point(3, 4)
20. What are comparison magic methods?
Comparison methods allow objects to be compared using operators like <, >, ==.
Example:
class Student:
def __init__(self, name, marks):
self.name = name
self.marks = marks
def __lt__(self, other):
return self.marks < other.marks
def __eq__(self, other):
return self.marks == other.marks
s1 = Student("Alice", 85)
s2 = Student("Bob", 90)
print(s1 < s2) # True
print(s1 == s2) # False
Advanced OOP Concepts
21. What is a class variable vs instance variable?
- Class variable: Shared by all instances
- Instance variable: Unique to each instance
Example:
class Counter:
total = 0 # class variable
def __init__(self, name):
self.name = name # instance variable
Counter.total += 1
c1 = Counter("First")
c2 = Counter("Second")
print(Counter.total) # 2
22. What is a static method?
A static method belongs to the class, not instances. It doesn't receive self or cls as the first parameter. Use @staticmethod decorator.
Example:
class Math:
@staticmethod
def add(x, y):
return x + y
print(Math.add(5, 3)) # 8 (no instance needed)
23. What is a class method?
A method that belongs to a class takes the class as its initial argument (cls). Employ the @classmethod decorator.
Example:
class Person:
count = 0
def __init__(self, name):
self.name = name
Person.count += 1
@classmethod
def get_count(cls):
return cls.count
p1 = Person("Alice")
p2 = Person("Bob")
print(Person.get_count()) # 2
24. What is a property decorator?
The @property decorator enables methods to be utilized in a manner similar to attributes, thereby offering functionality for both getting and setting values.
Example:
class Temperature:
def __init__(self):
self._celsius = 0
@property
def celsius(self):
return self._celsius
@celsius.setter
def celsius(self, value):
if value < -273.15:
raise ValueError("Temperature too low")
self._celsius = value
temp = Temperature()
temp.celsius = 25
print(temp.celsius) # 25
25. What is composition vs inheritance?
- Inheritance: "is-a" relationship (Dog is an Animal)
- Composition: "has-a" relationship (Car has an Engine)
Example of Composition:
class Engine:
def start(self):
return "Engine started"
class Car:
def __init__(self):
self.engine = Engine() # composition
def start(self):
return self.engine.start()
car = Car()
print(car.start()) # Engine started
Summary
Achieving proficiency in Object-Oriented Programming (OOP) principles within Python is essential for succeeding in technical interviews. It is important to engage in practice by applying these patterns and grasping the appropriate scenarios for utilizing each concept efficiently.