Python Programming - Inheritance

Exercise : Inheritance - General Questions
  • Inheritance - General Questions
81.
What is the purpose of the __str__() method in Python classes?
To define class attributes
To create a new instance of the class
To represent the object as a human-readable string
To access superclass attributes directly
Answer: Option
Explanation:
The __str__() method is used to provide a human-readable string representation of the object.

82.
Consider the following code:
class Animal:
    def __init__(self, species):
        self.species = species

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

83.
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.

84.
How can you achieve method overloading?
By declaring methods with different return types
By defining multiple methods with the same name but different parameters
By explicitly specifying the data type of method parameters
Method overloading is not supported in Python
Answer: Option
Explanation:
Python does not support method overloading in the traditional sense as it is done in languages like Java. Methods with the same name in a class will override each other.

85.
What is the purpose of the __setattr__() method in Python classes?
To define class attributes
To create a new instance of the class
To customize the behavior when an attribute is set
To access superclass attributes directly
Answer: Option
Explanation:
The __setattr__() method is used to customize the behavior when an attribute is set in a class.