Python OOP Zero to Hero Practice Test
Master Object-Oriented Programming in Python with Comprehensive Exercises
Key Takeaways
- Comprehensive Coverage: This practice test encompasses a wide range of OOP concepts from basic to advanced levels.
- Diverse Question Types: Includes multiple-choice questions, fill-in-the-blanks, and full coding challenges to enhance understanding.
- Real-World Applications: Incorporates LeetCode-level problems to prepare you for real-world programming scenarios.
Easy Section
Multiple Choice Questions (MCQs)
-
What is the primary purpose of a class in Python?
a) To store data
b) To define a blueprint for creating objects
c) To execute code
d) To import modulesAnswer: b) To define a blueprint for creating objects
-
Which keyword is used to create a class in Python?
a)def
b)class
c)object
d)newAnswer: b)
class -
What is the output of the following code?
python class Dog: def __init__(self, name): self.name = name dog = Dog("Buddy") print(dog.name) ```
a) None
b) Buddy
c) Dog
d) ErrorAnswer: b)
Buddy
Fill in the Blanks
-
The
______method is automatically called when an object is created from a class.
Answer:__init__ -
In Python, the
______keyword is used to refer to the current instance of a class.
Answer:self -
To make a method private in Python, you prefix its name with
______.
Answer:__(double underscore)
Coding Questions
-
Write a Python class named
Carwith the following attributes:make(string)model(string)year(integer)
Include a method
display_info()that prints the car's details in the format:
"Make: [make], Model: [model], Year: [year]"Answer:
class Car: def __init__(self, make, model, year): self.make = make self.model = model self.year = year def display_info(self): print(f"Make: {self.make}, Model: {self.model}, Year: {self.year}") car = Car("Toyota", "Corolla", 2020) car.display_info() -
Define a Python class
Rectanglewith attributeslengthandwidth, and a methodarea()that returns the area of the rectangle.Answer:
class Rectangle: def __init__(self, length, width): self.length = length self.width = width def area(self): return self.length * self.width rect = Rectangle(5, 10) print(rect.area()) # Output: 50
Medium Section
Multiple Choice Questions (MCQs)
-
What is the output of the following code?
python class Animal: def speak(self): print("Animal speaks") class Dog(Animal): def speak(self): print("Dog barks") dog = Dog() dog.speak() ```
a) Animal speaks
b) Dog barks
c) Error
d) NoneAnswer: b)
Dog barks -
Which of the following is an example of encapsulation?
a) Using private attributes with getters and setters
b) Inheriting from a base class
c) Overriding a method in a subclass
d) Using multiple inheritanceAnswer: a) Using private attributes with getters and setters
-
What does the
isinstance()function do in Python?
a) Checks if a class is a subclass of another
b) Checks if an object is an instance of a specific class
c) Creates a new instance of a class
d) Deletes an instance of a classAnswer: b) Checks if an object is an instance of a specific class
Fill in the Blanks
-
The
______function is used to check if an object is an instance of a specific class.
Answer:isinstance() -
In Python, you can use the
______method to define how an object should be represented as a string.
Answer:__str__ -
Complete the inheritance syntax:
python class Person: def __init__(self, name, age): self.name = name self.age = age class Student(____): def __init__(self, name, age, student_id): super().__init__(name, age) self.student_id = student_id ```
Answer: Person
Coding Questions
-
Create a Python class
BankAccountwith the following attributes:account_holder_name(string)balance(float)
Include the following methods:
-
deposit(amount)– adds theamountto the balance. -
withdraw(amount)– subtracts theamountfrom the balance if sufficient funds are available, otherwise prints"Insufficient funds".
Answer:
class BankAccount: def __init__(self, account_holder_name, balance=0.0): self.account_holder_name = account_holder_name self.balance = balance def deposit(self, amount): self.balance += amount print(f"Deposited ${amount}. New balance: ${self.balance}") def withdraw(self, amount): if amount > self.balance: print("Insufficient funds") else: self.balance -= amount print(f"Withdrew ${amount}. New balance: ${self.balance}") account = BankAccount("John Doe", 1000.0) account.deposit(500.0) account.withdraw(200.0) account.withdraw(1500.0) -
Create a Python class
Studentthat inherits from a base classPerson. ThePersonclass has attributesnameandage. TheStudentclass adds an attributestudent_idand a methoddisplay_info()that prints all attributes.Answer:
class Person: def __init__(self, name, age): self.name = name self.age = age class Student(Person): def __init__(self, name, age, student_id): super().__init__(name, age) self.student_id = student_id def display_info(self): print(f"Name: {self.name}, Age: {self.age}, Student ID: {self.student_id}") student = Student("Alice", 20, "S12345") student.display_info()
Hard Section
Multiple Choice Questions (MCQs)
-
What is the output of the following code?
python class A: def __init__(self): self.x = 1 class B(A): def __init__(self): super().__init__() self.y = 2 b = B() print(b.x, b.y) ```
a) 1 2
b) 2 1
c) Error
d) NoneAnswer: a)
1 2 -
Which of the following is an example of polymorphism?
a) A class inheriting from multiple classes
b) A method having the same name in different classes
c) A class overriding a method from its parent class
d) Both b and cAnswer: d) Both b and c
-
What does the
@staticmethoddecorator indicate in Python?
a) The method requires theselfparameter and can be called on an instance.
b) The method does not require theselfparameter and can be called on the class itself.
c) The method can access class-level variables.
d) None of the above.Answer: b) The method does not require the
selfparameter and can be called on the class itself.
Fill in the Blanks
-
The
______method is used to define how an object should be compared for equality.
Answer:__eq__ -
In Python, the
______function is used to delete an attribute from an object.
Answer:delattr() -
Complete the multi-level inheritance structure:
python class A: def display(self): print("I am in Class A") class B(A): def display(self): super().display() print("I am in Class B") class C(B): def display(self): super().display() print("I am in Class C") obj = C() obj.display() ```
Expected Output:
``` I am in Class A I am in Class B I am in Class C ```
Coding Challenges
Data Management System
Create a Python program with the following requirements:
- A class called
Contactthat has attributes –name,phone, andemail. - A manager class
ContactManagerthat uses a list to storeContactobjects. - Implement the following methods in
ContactManager: add_contact(contact): Adds a new contact to the list.delete_contact(name): Deletes a contact by name.get_all_contacts(): Displays all contacts.
Example Usage:
manager = ContactManager()
contact1 = Contact("Alice", "1234", "alice@example.com")
manager.add_contact(contact1)
manager.get_all_contacts()
manager.delete_contact("Alice")
Answer:
class Contact:
def __init__(self, name, phone, email):
self.name = name
self.phone = phone
self.email = email
class ContactManager:
def __init__(self):
self.contacts = []
def add_contact(self, contact):
self.contacts.append(contact)
print(f"Added contact: {contact.name}")
def delete_contact(self, name):
for contact in self.contacts:
if contact.name == name:
self.contacts.remove(contact)
print(f"Deleted contact: {name}")
return
print(f"Contact {name} not found.")
def get_all_contacts(self):
print("All Contacts:")
for contact in self.contacts:
print(f"Name: {contact.name}, Phone: {contact.phone}, Email: {contact.email}")
manager = ContactManager()
contact1 = Contact("Alice", "1234", "alice@example.com")
manager.add_contact(contact1)
manager.get_all_contacts()
manager.delete_contact("Alice")
manager.get_all_contacts()
Find Matching Shapes
Implement a Python program using OOP to solve the following:
You are provided with a Shape class that has the attribute area. Subclasses Rectangle and Circle override the calculate_area() method to compute their respective areas.
Write a function find_shapes_over_area(shapes, threshold) that accepts:
- A list of various shape objects.
- A threshold value.
The function should return a list of shapes where the area is greater than the threshold.
Example Usage:
shapes = [Rectangle(5, 10), Circle(7), Rectangle(2, 8)]
filtered_shapes = find_shapes_over_area(shapes, 50)
print(filtered_shapes) # Returns only the shapes whose areas > 50
Answer:
import math
class Shape:
def __init__(self):
self.area = 0
def calculate_area(self):
pass
class Rectangle(Shape):
def __init__(self, length, width):
super().__init__()
self.length = length
self.width = width
self.calculate_area()
def calculate_area(self):
self.area = self.length * self.width
class Circle(Shape):
def __init__(self, radius):
super().__init__()
self.radius = radius
self.calculate_area()
def calculate_area(self):
self.area = math.pi * (self.radius ** 2)
def find_shapes_over_area(shapes, threshold):
return [shape for shape in shapes if shape.area > threshold]
shapes = [Rectangle(5, 10), Circle(7), Rectangle(2, 8)]
filtered_shapes = find_shapes_over_area(shapes, 50)
for shape in filtered_shapes:
print(f"{shape.__class__.__name__} with area {shape.area}")
Conclusion
Mastering Object-Oriented Programming in Python requires a solid understanding of core concepts such as classes, objects, inheritance, polymorphism, and encapsulation. This practice test is designed to guide you from foundational knowledge to advanced application through a structured progression of questions. By diligently working through the Easy, Medium, and Hard sections, you will develop the skills necessary to tackle real-world programming challenges with confidence.
References
Last updated January 19, 2025