What is Python Inheritance? A Simple and Effective Introduction to the Is a Relationship between Classes

python 201 Object oriented programming inheritance

Python object-oriented programming inheritance is a way of creating new classes from existing ones by reusing and extending their functionality. Inheritance models what is called an is a relationship, which means that when you have a derived class that inherits from a base class, you create a relationship where the derived class is a specialized version of the base class.

For example, suppose you have a base class called Animal that has attributes like name and age and methods like eat and sleep. You can create a derived class called Dog that inherits from Animal and adds new attributes like breed and color and new methods like bark and fetch. A Dog object is an Animal object, but with more specific features.

To create a subclass or a child class in Python, you use the keyword class followed by the name of the subclass and the name of the base class in parentheses. For example, this is how you can define a Dog class that inherits from the Animal class:

class Dog(Animal):
  def init(self, name, age, breed, color):
    super().init(name, age) # Call the base class constructor
    self.breed = breed # Add a new attribute
    self.color = color # Add another new attribute

  def bark(self):
    print(f"{self.name} is barking.")

  def fetch(self, item):
    print(f"{self.name} is fetching {item}.")

To create an object or an instance of a subclass, you call the subclass name with parentheses and pass any arguments that the constructor requires. For example, this is how you can create a Dog object named rex:

rex = Dog("Rex", 3, "German Shepherd", "Brown")

You can access the attributes and methods of rex as well as those inherited from the Animal class. For example, this is how you can print the name, age, breed, and color of rex and call the eat, sleep, bark, and fetch methods:

print(rex.name) # Prints Rex
print(rex.age) # Prints 3
print(rex.breed) # Prints German Shepherd
print(rex.color) # Prints Brown
rex.eat("dog food") # Prints Rex is eating dog food.
rex.sleep() # Prints Rex is sleeping.
rex.bark() # Prints Rex is barking.
rex.fetch("ball") # Prints Rex is fetching ball.

Python also supports multiple inheritance, which is a way of creating a new class from two or more base classes. This allows you to combine features from different classes into one. However, multiple inheritance can also introduce complexity and ambiguity in your code, especially when there are conflicts or overlaps between the base classes.

Related posts

Leave a Comment