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()?
"Toyota Camry"
"Camry Toyota"
"Toyota"
"Camry"
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?
To check if an element is present
To calculate the length of an object
To define class attributes
To delete the class object
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)?
"The Great Gatsby F. Scott Fitzgerald"
"F. Scott Fitzgerald The Great Gatsby"
"The Great Gatsby by F. Scott Fitzgerald"
"F. Scott Fitzgerald by The Great Gatsby"
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?
To define iteration behavior
To calculate the length of an object
To delete the class object
To serialize the object
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()?
7
25
5
10
Answer: Option
Explanation:
The distance_from_origin method calculates the distance of the point from the origin using the distance formula.