Python Programming - Objects
Exercise : Objects - General Questions
- Objects - General Questions
26.
Consider the following Python code:
class Vehicle:
def __init__(self, brand, model):
self.brand = brand
self.model = model
def display_info(self):
return f"{self.brand} {self.model}"
If you create an instance of the `Vehicle` class called car with brand "Toyota" and model "Camry", what will be the result of calling car.display_info()?
Answer: Option
Explanation:
The
display_info method returns a string combining the brand and model attributes.
27.
What is the purpose of the
__contains__ method in Python classes?
Answer: Option
Explanation:
The
__contains__ method is used to check if a specified element is present in the object. It is called by functions like in.
28.
Consider the following Python code:
class Book:
def __init__(self, title, author):
self.title = title
self.author = author
def __str__(self):
return f"{self.title} by {self.author}"
If you create an instance of the `Book` class called my_book with title "The Great Gatsby" and author "F. Scott Fitzgerald", what will be the result of calling str(my_book)?
Answer: Option
Explanation:
The
__str__ method provides a human-readable string representation of the object, and calling str(my_book) returns the specified format.
29.
In Python, what is the purpose of the
__iter__ method in a class?
Answer: Option
Explanation:
The
__iter__ method is used to define how an object should behave when used in an iteration context, such as with a for loop.
30.
Consider the following Python code:
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
def distance_from_origin(self):
return (self.x ** 2 + self.y ** 2) ** 0.5
If you create an instance of the `Point` class called p with coordinates (3, 4), what will be the result of calling p.distance_from_origin()?
Answer: Option
Explanation:
The
distance_from_origin method calculates the distance of the point from the origin using the distance formula.
Quick links
Quantitative Aptitude
Verbal (English)
Reasoning
Programming
Interview
Placement Papers