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 modules
Answer: 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) new
Answer: 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) Error
Answer: b) Buddy
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)
Write a Python class named Car with 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 Rectangle with attributes length and width, and a method area() 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
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) None
Answer: 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 inheritance
Answer: 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 class
Answer: b) Checks if an object is an instance of a specific class
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
Create a Python class BankAccount with the following attributes:
account_holder_name (string)balance (float)Include the following methods:
deposit(amount) – adds the amount to the balance.
withdraw(amount) – subtracts the amount from 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 Student that inherits from a base class Person. The Person class has attributes name and age. The Student class adds an attribute student_id and a method display_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()
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) None
Answer: 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 c
Answer: d) Both b and c
What does the @staticmethod decorator indicate in Python?
a) The method requires the self parameter and can be called on an instance.
b) The method does not require the self parameter 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 self parameter and can be called on the class itself.
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
```
Create a Python program with the following requirements:
Contact that has attributes – name, phone, and email.ContactManager that uses a list to store Contact objects.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()
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:
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}")
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.