Boost your Python skills with these MCQs on Object-Oriented Programming and Inheritance. Ideal for beginners, students, and job seekers to test and strengthen their understanding of Python OOP concepts.
To reuse code and extend functionality
Inheritance allows code reuse and method overriding in child classes.
class Child(Parent):
In Python, a child class is defined using the syntax `class Child(Parent):`, where `Child` inherits from `Parent`.
class Animal:
def speak(self):
print("Animal speaks")
class Dog(Animal):
pass
d = Dog()
d.speak()
Animal speaks
Dog inherits the `speak()` method from Animal.
class Parent:
def __init__(self):
print("Parent constructor")
class Child(Parent):
def __init__(self):
print("Child constructor")
c = Child()
Child constructor
The `Child` constructor overrides the `Parent` constructor.
To enable code reusability
Inheritance helps avoid code duplication by allowing child classes to reuse methods and properties of parent classes.
class Child(Parent):
In Python, inheritance is denoted by placing the parent class name in parentheses after the child class name.
class Parent:
def show(self):
print("Parent")
class Child(Parent):
def show(self):
print("Child")
obj = Child()
obj.show()
Child
class Parent:
def greet(self):
print("Hello from Parent!")
class Child(Parent):
def greet(self):
print("Hello from Child!")
obj = Child()
obj.greet()
Hello from Child!
The `greet` method is overridden in the `Child` class, so that version is called.
Calls a method from the parent class
`super()` is used to call methods from the parent class, especially in method overrides
C3 linearization
Python uses C3 linearization to determine the order in which classes are searched when executing a method.
true
If `child_obj` is an instance of a class derived from `Parent`, `isinstance` will return `True`.
Cascading
Python supports single, multiple, and multilevel inheritance, but "cascading" is not a recognized inheritance type.
Both A and C
You can call a parent method using either `Parent.method(self)` or `super().method()`.
They are inaccessible due to name mangling
Private members with double underscores are name-mangled and not directly accessible from subclasses.
Combining multiple types of inheritance
Hybrid inheritance is a combination of more than one type of inheritance, like multiple and multilevel.