Exercise: Objects

Questions for: Objects

Consider the following Python code:
class Student:
    def __init__(self, name, age):
        self.name = name
        self.age = age

    def birthday(self):
        self.age += 1
If you create an instance of the Student class called john with age 20 and then call john.birthday(), what will be the updated age?
A:
20
B:
21
C:
19
D:
None
Answer: B
The birthday method increments the age attribute by 1, so after calling john.birthday(), the updated age will be 21.
In Python, what is the purpose of the __str__ method in a class?
A:
To convert the object to a string representation
B:
To create a new instance of the class
C:
To define class attributes
D:
To delete the class object
Answer: A
The __str__ method is used to define a human-readable string representation of the object when the str() function is called.
Consider the following Python code:
class BankAccount:
    def __init__(self, balance):
        self.balance = balance

    def withdraw(self, amount):
        if amount <= self.balance:
            self.balance -= amount
            return True
        else:
            return False
What does the withdraw method return if the withdrawal is successful?
A:
True
B:
False
C:
The updated balance
D:
None
Answer: A
The withdraw method returns True if the withdrawal is successful, indicating that the amount was deducted from the balance.
Which method is automatically called when an object is created?
A:
__new__
B:
__create__
C:
__init__
D:
__construct__
Answer: C
The __init__ method is automatically called when an object is created in Python, allowing you to initialize the object's attributes.
Consider the following Python code:
class Circle:
    def __init__(self, radius):
        self.radius = radius

    def calculate_area(self):
        return 3.14 * self.radius * self.radius
How would you create an instance of the Circle class with a radius of 5?
A:
circle_instance = Circle.create(5)
B:
circle_instance = Circle(radius=5)
C:
circle_instance = new Circle(5)
D:
circle_instance = Circle(5)
Answer: B
The correct way to create an instance of the Circle class with a radius of 5 is to use the constructor and pass the value as a named argument.
Ad Slot (Above Pagination)
Quiz