Exercise: Python

Questions for: Inheritance

How does Python handle multiple inheritance conflicts for attribute resolution?
A:
By automatically resolving conflicts using the first defined attribute
B:
By raising an error and requiring explicit resolution using super()
C:
By using the C3 linearization algorithm to determine attribute resolution order
D:
Multiple inheritance conflicts are not allowed in Python
Answer: A
Python automatically resolves attribute conflicts in multiple inheritance by using the attribute defined in the first class.
Consider the following code:
class Vehicle:
    def __init__(self, brand):
        self.brand = brand

class Car(Vehicle):
    def __init__(self, brand, model):
        super().__init__(brand)
        self.model = model
What is the primary purpose of using super().__init__(brand) in the Car class constructor?
A:
To call the constructor of the Car class
B:
To create a new instance of the Vehicle class
C:
To initialize attributes of the Vehicle class in the Car class
D:
To access superclass attributes directly
Answer: C
super().__init__(brand) is used to call the constructor of the superclass Vehicle and initialize the brand attribute.
In Python, what is the purpose of the isinstance() function?
A:
To check if an object is an instance of a class
B:
To check if a class is a subclass of another class
C:
To check if two classes have the same attributes
D:
To check if an object has a specific attribute
Answer: A
The isinstance() function is used to check if an object is an instance of a particular class or a tuple of classes.
In Python, what is the purpose of the @property decorator?
A:
To create a new instance of the class
B:
To define a method that can be accessed like an attribute
C:
To access class attributes directly
D:
To define a method that can be accessed as a read-only attribute
Answer: D
The @property decorator is used to define a method that can be accessed as a read-only attribute, providing a getter method.
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?
A:
To call the constructor of the Cat class
B:
To create a new instance of the Animal class
C:
To initialize attributes of the Animal class in the Cat class
D:
To access superclass attributes directly
Answer: C
super().__init__(species) is used to call the constructor of the superclass Animal and initialize the species attribute.
Ad Slot (Above Pagination)
Quiz