Inheritance - Rybd04/2143-OOP GitHub Wiki

Definition

Inheritance

Inheritance is the mechanism by which one class (called the child or subclass) derives or inherits the features of another class (called the parent or superclass).

Explanation

This allows a class to inherit properties such as methods or variables from an already created parent class.

Basic Code Example

class Animal:  # Parent class
    def speak(self):
        return "Some sound"

class Dog(Animal):  # Child class inherits from Animal
    def speak(self):
        return "Bark"

class Cat(Animal):
    def speak(self):
        return "Meow"

a = Dog()
print(a.speak())  # Output: Bark

Dog and Cat inherit from Animal.

They override the speak() method to provide specific behavior.

Image

image

Additional Resources

https://www.codecademy.com/resources/blog/what-is-inheritance/ https://stackify.com/oop-concept-inheritance/