Exercise: Objects

Questions for: Objects

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()?
A:
7
B:
25
C:
5
D:
10
Answer: C
The distance_from_origin method calculates the distance of the point from the origin using the distance formula.
In Python, what is the purpose of the __iter__ method in a class?
A:
To define iteration behavior
B:
To calculate the length of an object
C:
To delete the class object
D:
To serialize the object
Answer: A
The __iter__ method is used to define how an object should behave when used in an iteration context, such as with a for loop.
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)?
A:
"The Great Gatsby F. Scott Fitzgerald"
B:
"F. Scott Fitzgerald The Great Gatsby"
C:
"The Great Gatsby by F. Scott Fitzgerald"
D:
"F. Scott Fitzgerald by The Great Gatsby"
Answer: C
The __str__ method provides a human-readable string representation of the object, and calling str(my_book) returns the specified format.
What is the purpose of the __contains__ method in Python classes?
A:
To check if an element is present
B:
To calculate the length of an object
C:
To define class attributes
D:
To delete the class object
Answer: A
The __contains__ method is used to check if a specified element is present in the object. It is called by functions like in.
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()?
A:
"Toyota Camry"
B:
"Camry Toyota"
C:
"Toyota"
D:
"Camry"
Answer: A
The display_info method returns a string combining the brand and model attributes.
Ad Slot (Above Pagination)
Quiz