Python Interview Questions - Modules & OOP
Master Python interview questions on Modules, Exception Handling, and Object-Oriented Programming (OOP).
Master Python interview questions on Modules, Exception Handling, and Object-Oriented Programming (OOP). This interview-focused guide covers essential python interview questions - modules & oop concepts for technical interviews.
Python Interview Questions – Level 3: Modules, OOP & Exceptions
This level dives into software architecture, error resilience, and the core principles of Object-Oriented Programming in Python.
121. What is a module?
A module is a file containing Python definitions and statements. The file name is the module name with the suffix .py appended.
Example:
# Create a file called my_module.py with this code:
def greet(name):
print(f"Hello, {name}!")
PI = 3.14159
# Now you can import and use it!
# import my_module
# my_module.greet("Alice")
# print(my_module.PI)
122. What is import?
The import statement is used to make code available from another module.
Example:
import math
print(math.sqrt(16)) # 4.0
123. Difference between import and from import?
import module: Imports the entire module. You access its contents viamodule.function().from module import function: Imports specific attributes. You access them directly asfunction().
Example:
# Import entire module
import math
print(math.pi) # 3.1415...
# Import specific attribute
from math import pi
print(pi) # 3.1415...
124. What is __init__.py?
__init__.py is used to mark a directory as a Python package. It is executed when the package or a module in the package is imported. In Python 3.3+, it's optional, but still recommended for initialization logic.
Example:
# Directory structure:
# my_package/
# __init__.py
# module1.py
# module2.py
# Inside __init__.py
# from .module1 import func1
# from .module2 import func2
125. What is a package?
A package is a way of structuring Python’s module namespace by using "dotted module names". It is essentially a directory containing a collection of modules and an __init__.py file.
Example:
# Directory structure:
# ecommerce/
# __init__.py
# products.py
# checkout.py
# Importing from the package
# from ecommerce.products import Product
126. What is sys module?
The sys module provides access to variables used or maintained by the interpreter and functions that interact strongly with the interpreter (e.g., sys.path, sys.argv).
Example:
import sys
print(sys.version) # Python version info
print(sys.argv) # Command-line arguments
127. What is os module?
The os module provides a portable way of using operating system-dependent functionality like interacting with the file system.
Example:
import os
print(os.getcwd()) # Current working directory
128. What is datetime module?
Used for manipulating dates and times with classes like date, time, datetime, and timedelta.
Example:
from datetime import datetime, timedelta
now = datetime.now()
print(now)
tomorrow = now + timedelta(days=1)
print(tomorrow)
129. What is random module?
Used to generate pseudo-random numbers and select random elements from sequences.
Example:
import random
print(random.randint(1, 10)) # Random number between 1-10
print(random.choice(["apple", "banana", "cherry"])) # Random choice
130. What is math module?
Provides access to mathematical functions like sqrt(), sin(), and constants like pi.
Example:
import math
print(math.sqrt(25)) # 5
print(math.pi) # 3.1415...
131. What is exception?
An exception is an error that occurs during program execution. Python generates an exception that can be handled to prevent a crash.
Example:
# This code raises an exception
# print(10 / 0) # ZeroDivisionError
132. What is try-except?
The try-except block is used to catch and handle exceptions.
try:
x = 1 / 0
except ZeroDivisionError:
print("Cannot divide by zero!")
133. What is finally?
The finally block contains code that always executes, regardless of whether an exception occurred. It's used for cleanup actions.
Example:
try:
file = open("test.txt", "r")
content = file.read()
except FileNotFoundError:
print("File not found!")
finally:
if 'file' in locals():
file.close() # Always runs!
134. What is raise?
The raise keyword is used to manually trigger an exception.
Example:
def validate_age(age):
if age < 18:
raise ValueError("Must be 18 or older!")
print("Valid age!")
# validate_age(17) # Raises ValueError
135. What are built-in exceptions?
Standard exceptions like IndexError, KeyError, ValueError, and TypeError.
Example:
# IndexError
my_list = [1, 2, 3]
try:
print(my_list[10])
except IndexError:
print("Index out of range!")
136. What is custom exception?
A user-defined exception created by inheriting from the built-in Exception class.
Example:
class InsufficientBalanceError(Exception):
pass
class BankAccount:
def __init__(self, balance):
self.balance = balance
def withdraw(self, amount):
if amount > self.balance:
raise InsufficientBalanceError("Not enough money!")
self.balance -= amount
return self.balance
account = BankAccount(100)
try:
account.withdraw(150)
except InsufficientBalanceError as e:
print(e)
137. What is OOP?
Object-Oriented Programming (OOP) is a paradigm based on "objects" that contain data (attributes) and code (methods).
Example:
class Dog:
def __init__(self, name):
self.name = name
def bark(self):
print(f"{self.name} says Woof!")
my_dog = Dog("Buddy")
my_dog.bark()
138. What is class?
A class is a blueprint or template for creating objects.
Example:
class Person:
pass # Empty class for now
# Create an object (instance)
alice = Person()
print(alice) # <__main__.Person object at ...>
139. What is object?
An object is an instance of a class.
Example:
class Car:
def __init__(self, make, model):
self.make = make
self.model = model
my_car = Car("Toyota", "Camry") # my_car is an object
print(my_car.make) # Toyota
140. What is __init__ method?
The __init__ method is the constructor of a class, called automatically when a new object is created.
Example:
class Student:
def __init__(self, name, roll_number):
self.name = name
self.roll_number = roll_number
s1 = Student("Alice", 101)
print(s1.name) # Alice
141. What is self?
self represents the instance of the class, allowing access to its attributes and methods.
Example:
class Circle:
def __init__(self, radius):
self.radius = radius # self.radius is instance variable
def area(self):
return 3.14 * self.radius * self.radius
c = Circle(5)
print(c.area()) # 78.5
142. What is instance variable?
Variables unique to each instance, typically defined in __init__ using self.
Example:
class Counter:
def __init__(self):
self.count = 0 # Instance variable
def increment(self):
self.count += 1
c1 = Counter()
c2 = Counter()
c1.increment()
print(c1.count) # 1
print(c2.count) # 0 (each has its own count!)
143. What is class variable?
Variables shared by all instances of a class, defined directly in the class body.
Example:
class Employee:
company = "Tech Corp" # Class variable (shared)
def __init__(self, name):
self.name = name
e1 = Employee("Alice")
e2 = Employee("Bob")
print(e1.company) # Tech Corp
print(e2.company) # Tech Corp (same!)
144. What is inheritance?
Allows a class (child) to acquire properties and methods from another class (parent).
Example:
class Animal: # Parent class
def eat(self):
print("Eating...")
class Dog(Animal): # Child class inherits from Animal
def bark(self):
print("Woof!")
my_dog = Dog()
my_dog.eat() # Inherited method!
my_dog.bark() # Own method!
145. Types of inheritance?
Includes Single, Multiple, Multilevel, Hierarchical, and Hybrid inheritance.
Example:
# Single inheritance
class Parent:
pass
class Child(Parent):
pass
# Multiple inheritance
class A:
pass
class B:
pass
class C(A, B):
pass
146. What is method overriding?
When a subclass provides a new implementation for a method already defined in its parent class.
Example:
class Animal:
def make_sound(self):
print("Generic animal sound")
class Cat(Animal):
def make_sound(self): # Overriding!
print("Meow!")
cat = Cat()
cat.make_sound() # Meow! (not generic)
147. What is super()?
A function used to call methods from the parent class, often used for initialization.
Example:
class Animal:
def __init__(self, name):
self.name = name
class Dog(Animal):
def __init__(self, name, breed):
super().__init__(name) # Call parent __init__
self.breed = breed
my_dog = Dog("Buddy", "Golden Retriever")
print(my_dog.name) # Buddy
print(my_dog.breed) # Golden Retriever
148. What is polymorphism?
Allows different classes to be treated as instances of the same class through inheritance.
Example:
class Bird:
def fly(self):
pass # Empty implementation
class Sparrow(Bird):
def fly(self):
print("Flying high!")
class Penguin(Bird):
def fly(self):
print("Can't fly, but can swim!")
def make_bird_fly(bird):
bird.fly() # Works for any Bird subclass!
sparrow = Sparrow()
penguin = Penguin()
make_bird_fly(sparrow)
make_bird_fly(penguin)
149. What is encapsulation?
Wrapping data and methods into a single unit (class) and restricting direct access (data hiding).
Example:
class BankAccount:
def __init__(self):
self.__balance = 0 # Private variable (double underscore)
def deposit(self, amount):
if amount > 0:
self.__balance += amount
def get_balance(self):
return self.__balance
account = BankAccount()
account.deposit(100)
print(account.get_balance()) # 100
# print(account.__balance) # AttributeError (can't access directly!)
150. What is abstraction?
Hiding complex implementation details and showing only essential features, often using Abstract Base Classes (ABC).
Example:
from abc import ABC, abstractmethod
class Shape(ABC): # Abstract Base Class
@abstractmethod
def area(self):
pass # Must be implemented by subclasses
class Rectangle(Shape):
def __init__(self, width, height):
self.width = width
self.height = height
def area(self): # Implement abstract method
return self.width * self.height
rect = Rectangle(5, 10)
print(rect.area()) # 50
151. What is private variable?
Achieved using a double underscore prefix (__var), which triggers name mangling in Python.
Example:
class MyClass:
def __init__(self):
self.__private_var = 42
obj = MyClass()
# print(obj.__private_var) # AttributeError
152. What is protected member?
Indicated by a single underscore (_var), signaling that it's intended for internal use.
Example:
class MyClass:
def __init__(self):
self._protected_var = 100
obj = MyClass()
print(obj._protected_var) # 100 (accessible, but convention says don't)
153. What is multiple inheritance?
When a class inherits from more than one parent class.
Example:
class A:
def method_a(self):
print("A's method")
class B:
def method_b(self):
print("B's method")
class C(A, B):
pass
obj = C()
obj.method_a()
obj.method_b()
154. What is method resolution order (MRO)?
The order in which Python searches for methods in a class hierarchy, determined by the C3 Linearization algorithm.
Example:
class A:
pass
class B(A):
pass
class C(A):
pass
class D(B, C):
pass
print(D.__mro__) # Shows search order!
155. What is __str__?
Returns a user-friendly string representation of an object.
Example:
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def __str__(self):
return f"Person: {self.name}, Age: {self.age}"
p = Person("Alice", 25)
print(p) # Person: Alice, Age: 25
156. What is __repr__?
Returns an "official" string representation of an object, used for debugging.
Example:
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def __repr__(self):
return f"Person('{self.name}', {self.age})"
p = Person("Alice", 25)
print(repr(p)) # Person('Alice', 25)
157. What is isinstance()?
Checks if an object is an instance of a specific class or its subclasses.
Example:
class Dog:
pass
my_dog = Dog()
print(isinstance(my_dog, Dog)) # True
print(isinstance(my_dog, object)) # True (all inherit from object)
158. What is issubclass()?
Checks if a class is a derived class of another class.
Example:
class Animal:
pass
class Cat(Animal):
pass
print(issubclass(Cat, Animal)) # True
print(issubclass(Cat, object)) # True
159. What is dataclass?
A decorator that automatically generates __init__, __repr__, etc., for classes that primarily store data.
Example:
from dataclasses import dataclass
@dataclass
class Point:
x: int
y: int
p = Point(5, 10)
print(p) # Point(x=5, y=10) (automatically generated __repr__)
160. What is namedtuple?
A factory function from collections for creating tuple subclasses with named fields.
Example:
from collections import namedtuple
Point = namedtuple('Point', ['x', 'y'])
p = Point(5, 10)
print(p.x) # 5
print(p.y) # 10
print(p[0]) # 5 (still acts like a tuple!)