Learning Sections show
Inheritance in Python
Inheritance is a fundamental concept in object-oriented programming (OOP) that allows a class to inherit attributes and methods from another class. The class that inherits is called the child class or subclass, and the class being inherited from is called the parent class or superclass.
Basic Inheritance
In Python, a child class inherits from a parent class by specifying the parent class in parentheses after the child class name.
Example:
class Animal:
def __init__(self, name):
self.name = name
def speak(self):
raise NotImplementedError("Subclass must implement this method")
class Dog(Animal):
def speak(self):
return "Woof!"
class Cat(Animal):
def speak(self):
return "Meow!"
# Create instances of Dog and Cat
dog = Dog("Buddy")
cat = Cat("Whiskers")
# Call the speak method on each instance
print(dog.speak()) # Output: Woof!
print(cat.speak()) # Output: Meow!