Hello once more, Pythonistas! Today, we’re digging deeper into the realm of Object-Oriented Programming (OOP) with a basic notion - ‘Inheritance’. Consider it similar to how traits are passed on from parents to children, except in Python! In Python, the term ‘inheritance’ refers to the ability to define a class (child class or derived class) that inherits all of the methods and properties of another class (parent class or base class). It’s a useful feature that encourages code reuse and organization. Here’s an easy way to see how inheritance works in Python:*# Parent class****class Bird:** def init(self):** print(“Bird is ready”)** def who_is_this(self):** print(“Bird”)** def swim(self):** print(“Swim faster”)**# Child class****class Penguin(Bird):**** def init(self):** super(). init() # call super() function****** print(“Penguin is ready”)** def who_is_this(self):** print(“Penguin”)** def run(self):** print(“Run faster”)***In this case, the ‘Penguin’ child class inherits from the **‘Bird’ **parent class. Before the ‘init()’ method, we employ the ‘super()’ function. This is because we want to copy the text of the parent class’s **‘init()**’ function into the child class.
Exercise
Excited to try out inheritance yourself? Let’s get to it:- Define a class **Animal**
with a method **say_hello**
that prints “Hello from Animal”.
- Create a child class
**Dog**
that inherits from**Animal**
and has a method**bark**
which prints “Woof woof!”. - Create an object from the
**Dog**
class and call both methods.
Conclusion
You’ve just learned about the intriguing idea of inheritance in Python. Inheritance is a key component of OOP, allowing us to create large systems with reusable and maintainable code. It may be difficult to understand at first, but with practice, you’ll discover how inheritance can make your coding life much easier. Keep coding, and the Python spirit will live on!