Which of the following is true about inheritance in Python?

Which of the following is true about inheritance in Python?

a) Inheritance allows a class to inherit properties and methods from another class
b) Inheritance restricts a class from using methods of another class
c) Inheritance duplicates all properties and methods of a class
d) Inheritance is not supported in Python

Answer:

a) Inheritance allows a class to inherit properties and methods from another class

Explanation:

Inheritance in Python is a mechanism where a new class, known as a derived or child class, inherits the properties and methods of an existing class, known as a base or parent class. This allows for code reusability and the extension of existing functionality.

class Animal:
def __init__(self, name):
    self.name = name

def speak(self):
    return f"{self.name} makes a sound"

class Dog(Animal):
def speak(self):
    return f"{self.name} barks"

# Creating an object of Dog class
dog = Dog("Buddy")
print(dog.speak())  # Output: Buddy barks

In this example, the Dog class inherits from the Animal class and overrides the speak() method to provide a more specific behavior. The Dog class can also access other methods and attributes of the Animal class.

Inheritance promotes code reuse and makes it easier to create and maintain hierarchical relationships between classes.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top