Exercise: Python

Questions for: Inheritance

Consider the following code:
class Animal:
    def speak(self):
        print("Animal speaks")

class Dog(Animal):
    def speak(self):
        print("Dog barks")

def main():
    my_pet = Dog()
    my_pet.speak()
What will be the output of the main() function?
A:
Animal speaks
B:
Dog barks
C:
The code will result in an error
D:
Animal barks
Answer: B
The speak() method is overridden in the Dog class, so calling speak() on a Dog instance will print "Dog barks".
How does Python handle 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 case of diamond inheritance conflicts.
In Python, what is the purpose of the super() function?
A:
To define class attributes
B:
To create a new instance of the class
C:
To access superclass methods and attributes
D:
To access subclass methods and attributes
Answer: C
The super() function is used to access methods and attributes of the superclass in Python.
What is the purpose of the __slots__ attribute in Python classes?
A:
To define class attributes
B:
To create a new instance of the class
C:
To restrict the set of attributes that can be assigned to instances
D:
To access superclass attributes directly
Answer: C
The __slots__ attribute is used to restrict the set of attributes that can be assigned to instances, providing memory optimization.
What is the purpose of the __bases__ attribute in Python classes?
A:
To define class attributes
B:
To create a new instance of the class
C:
To access the base classes of a class
D:
To access superclass attributes directly
Answer: C
The __bases__ attribute is used to access the base classes of a class in Python.
Ad Slot (Above Pagination)
Quiz