Exercise: Inheritance
Questions for: Inheritance
What is the purpose of the
__str__() method in Python classes?
A:
To define class attributes
B:
To create a new instance of the class
C:
To represent the object as a human-readable string
D:
To access superclass attributes directly
Answer: C
The
__str__() method is used to provide a human-readable string representation of the object.
How does Python handle method resolution in the presence of diamond inheritance conflicts?
A:
By automatically resolving conflicts using the first defined method
B:
By raising an error and requiring explicit resolution using
super()
C:
By using the C3 linearization algorithm to determine method resolution order
D:
Diamond inheritance conflicts are not allowed in Python
Answer: C
Python uses the C3 linearization algorithm to determine the method resolution order in the presence of diamond inheritance conflicts.
Discuss About this Question.
Consider the following code:
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
class Employee(Person):
def __init__(self, name, age, employee_id):
super().__init__(name, age)
self.employee_id = employee_id
What is the primary advantage of using super().__init__(name, age) in the Employee class constructor?
A:
To call the constructor of the
Employee class
B:
To create a new instance of the
Person class
C:
To initialize attributes of the
Person class in the Employee class
D:
To access superclass attributes directly
Answer: C
super().__init__(name, age) is used to call the constructor of the superclass Person and initialize the name and age attributes.Discuss About this Question.
In Python, what is the purpose of the
__repr__() method in a class?
A:
To define class attributes
B:
To create a new instance of the class
C:
To represent the object as a string for debugging
D:
To access superclass attributes directly
Answer: C
The
__repr__() method is used to provide a string representation of the object, often for debugging purposes.Discuss About this Question.
What is the purpose of the
__call__() method in a Python class?
A:
To create a new instance of the class
B:
To define class attributes for the class
C:
To customize the behavior when an instance of the class is called
D:
To access superclass attributes directly
Answer: C
The
__call__() method in a class is used to customize the behavior when an instance of the class is called, allowing instances to be callable.Discuss About this Question.
Ad Slot (Above Pagination)
Discuss About this Question.