Python Programming - Inheritance

Exercise : Inheritance - General Questions
  • Inheritance - General Questions
101.
In Python, what is the purpose of the __str__() method in a class?
To define class attributes
To create a new instance of the class
To represent the object as a string for debugging
To provide a human-readable string representation of the object
Answer: Option
Explanation:
The __str__() method is used to provide a human-readable string representation of the object.

102.
Consider the following code:
class Bird:
    def __init__(self, species):
        self.species = species

class Parrot(Bird):
    def __init__(self, species, color):
        super().__init__(species)
        self.color = color
What is the primary purpose of using super().__init__(species) in the Parrot class constructor?
To call the constructor of the Parrot class
To create a new instance of the Bird class
To initialize attributes of the Bird class in the Parrot class
To access superclass attributes directly
Answer: Option
Explanation:
super().__init__(species) is used to call the constructor of the superclass Bird and initialize the species attribute.

103.
In Python, what is the purpose of the @property decorator?
To create a new instance of the class
To define a method that can be accessed like an attribute
To access class attributes directly
To define a method that can be accessed as a read-only attribute
Answer: Option
Explanation:
The @property decorator is used to define a method that can be accessed as a read-only attribute, providing a getter method.

104.
How does Python handle multiple inheritance conflicts for attribute resolution?
By automatically resolving conflicts using the first defined attribute
By raising an error and requiring explicit resolution using super()
By using the C3 linearization algorithm to determine attribute resolution order
Multiple inheritance conflicts are not allowed in Python
Answer: Option
Explanation:
Python automatically resolves attribute conflicts in multiple inheritance by using the attribute defined in the first class.

105.
What is the purpose of the __slots__ attribute in Python classes?
To define class attributes
To create a new instance of the class
To restrict the set of attributes that can be assigned to instances
To access superclass attributes directly
Answer: Option
Explanation:
The __slots__ attribute is used to restrict the set of attributes that can be assigned to instances, providing memory optimization.