13.4 Hierarchical inheritance

3 min readjune 24, 2024

in Python lets you create a family tree of classes. It's like having a that passes down traits to multiple child classes, each with their own unique features.

This powerful tool helps you organize and reuse code efficiently. You can build complex structures, from general to specific, allowing for flexible and modular programming in object-oriented design.

Hierarchical Inheritance in Python

Key features of hierarchical inheritance

Top images from around the web for Key features of hierarchical inheritance
Top images from around the web for Key features of hierarchical inheritance
  • Involves creating a (parent) and multiple derived classes (children)
    • Base contains common attributes and methods shared by derived classes ( class with method)
    • Derived classes inherit these attributes and methods ( and classes inherit from Animal)
  • Derived classes can have their own specific attributes and methods in addition to inherited ones
    • Allows for specialization and customization of derived classes (Cat class with method, Dog class with method)
  • Enables code reuse and creation of specialized classes
    • Avoids duplication of common code in derived classes
    • Derived classes can override or extend inherited methods as needed (Dog class overrides eat() method)
  • [isinstance()](https://www.fiveableKeyTerm:isinstance())
    function checks if an object is an instance of a specific class or any of its parent classes
    • Helps determine the type and relationships of objects (
      isinstance(cat, Animal)
      returns
      True
      )

Class structure design for inheritance

  • Identify common attributes and behaviors shared by derived classes
    • Define these common elements in the base class (Animal class with attribute and eat() method)
  • Determine specialized attributes and behaviors specific to each
    • Cat class with attribute and meow() method
    • Dog class with attribute and bark() method
  • Create base class () with shared attributes and methods
    • class Animal:
      with
      def [__init__](https://www.fiveableKeyTerm:__init__)(self, name):
      and
      def eat(self):
  • Create each derived class (), inheriting from base class using
    class DerivedClass(BaseClass):
    syntax
    • class Cat(Animal):
      and
      class Dog(Animal):
  • Add specific attributes and methods to each derived class as needed
    • def __init__(self, name, color):
      and
      def meow(self):
      in Cat class
    • def __init__(self, name, breed):
      and
      def bark(self):
      in Dog class

Multilevel inheritance for tree-like organization

  • Involves creating a hierarchy of classes with multiple levels
    • Base class (Animal) serves as parent for one or more derived classes ()
    • Derived classes can serve as parent classes for further derived classes (Cat and Dog inherit from Mammal)
  • Each class in hierarchy inherits attributes and methods from its parent class
    • Allows for creation of tree-like structure of classes (Animal → Mammal → Cat/Dog)
  • When accessing attributes or methods, Python searches in current class, then parent class, and continues up hierarchy until found or top reached ()
    • Cat object can access eat() method defined in Animal class
  • Enables creation of increasingly specialized classes
    • Each level in hierarchy adds more specific attributes and behaviors (Mammal class adds method, Cat class adds meow() method)

Object-Oriented Programming Concepts in Hierarchical Inheritance

  • Inheritance: Allows classes to inherit attributes and methods from other classes
  • : Bundles data and methods that operate on that data within a single unit or object
  • Subclass: A class that inherits from another class, also known as a derived class
  • Superclass: A class from which other classes inherit, also known as a base class

Key Terms to Review (35)

__init__: __init__ is a special method in Python that is automatically called when an object of a class is created. It is used to initialize the attributes of the object, setting them to their starting values.
Animal: An animal is a living organism that is capable of independent movement, possesses specialized sensory organs, and typically derives energy from the consumption of organic material. Animals are multicellular eukaryotes that belong to the kingdom Animalia, distinguished from plants, fungi, and other forms of life.
Bark(): The bark() function is a method in object-oriented programming that allows an object to produce a specific sound. It is commonly associated with the concept of hierarchical inheritance, where derived classes inherit properties and methods from a base class, including the ability to produce a characteristic sound through the bark() method.
Base Class: A base class, also known as a superclass, is the fundamental class from which other classes inherit properties and methods. It serves as the foundation for creating more specialized classes, allowing for the reuse of common functionality and the establishment of hierarchical relationships between classes.
Breed: In the context of hierarchical inheritance, a breed refers to a distinct group or type within a species that shares common characteristics, often the result of selective breeding. Breeds are a fundamental concept in understanding how inheritance and genetic traits are passed down through generations within a species.
Cat: A cat is a small, carnivorous mammal that is widely kept as a pet. Cats are known for their agility, independent nature, and ability to climb, hunt, and sleep for long periods of time.
Child Class: A child class, also known as a subclass, is a class that inherits properties and methods from a parent or base class, known as the superclass. Child classes can extend and modify the functionality of the parent class, allowing for the creation of specialized and customized versions of the original class.
Class: A class is a blueprint for creating objects, encapsulating data for the object and methods to manipulate that data. It allows for the creation of user-defined data structures.
Class: In the context of programming, a class is a blueprint or template that defines the structure and behavior of objects. It serves as a blueprint for creating objects, which are instances of the class, and encapsulates data and functionality within a cohesive unit.
Class ChildClass(ParentClass):: This notation defines a new class called 'ChildClass' that inherits properties and methods from an existing class named 'ParentClass'. It shows how hierarchical inheritance works in programming, allowing subclasses to extend or modify the functionality of their parent classes. This promotes code reuse and establishes a clear relationship between classes, making it easier to manage and organize code in a structured manner.
Color: Color is a visual property of light that is perceived by the human eye and brain. It is a fundamental aspect of visual perception, influencing our understanding and interpretation of the world around us. In the context of hierarchical inheritance, color plays a crucial role in the way objects and their relationships are represented and understood within a class hierarchy.
Derived class: A derived class is a type of class in object-oriented programming that inherits properties and behaviors (methods) from another class, known as the base class. This allows the derived class to extend or modify the functionalities of the base class while retaining its core features. The relationship between derived and base classes forms the foundation for various inheritance structures, enabling code reuse and more organized program design.
Dog: A dog is a domesticated carnivorous mammal that has been bred in a wide variety of breeds for a multitude of purposes, including companionship, herding, hunting, and security. As a highly adaptable species, dogs have become one of the most popular and widely kept animals in the world.
Eat(): The eat() function is a method commonly used in the context of object-oriented programming, particularly in the topic of hierarchical inheritance. It represents an action or behavior that an object can perform, allowing it to consume or interact with other objects or resources within a program's structure.
Encapsulation: Encapsulation is a fundamental concept in object-oriented programming (OOP) that involves bundling data and methods into a single unit, known as a class. It is the mechanism that allows objects to hide their internal implementation details from the outside world, providing a well-defined interface for interacting with the object.
Hierarchical inheritance: Hierarchical inheritance is a type of inheritance in object-oriented programming where multiple derived classes inherit from a single base class. This allows for shared functionality and attributes to be defined in the base class and reused across multiple subclasses.
Hierarchical Inheritance: Hierarchical inheritance is a fundamental concept in object-oriented programming where a derived class inherits properties and methods from one or more base classes, forming a hierarchical relationship. This allows for the creation of complex class structures and the reuse of code across multiple levels of the hierarchy.
Inheritance: Inheritance is a fundamental concept in object-oriented programming where a new class is created based on an existing class, inheriting its attributes and behaviors. This allows for code reuse, hierarchical organization, and the creation of specialized classes that build upon the foundation of more general ones.
Isinstance(): The isinstance() function in Python is used to check the type of an object. It determines whether an object is an instance of a specified class or any of its subclasses. This function is particularly useful when working with variables, type conversion, mixed data types, boolean values, inheritance, and hierarchical inheritance.
Mammal: Mammals are a class of warm-blooded vertebrate animals that are characterized by the presence of hair, the ability to produce milk to feed their young, and a neocortex region in their brain. They are the most diverse and widespread group of animals on Earth, ranging from the tiny bumblebee bat to the massive blue whale.
Meow(): meow() is a method or function that is commonly associated with objects or instances of a class that represents a cat or feline creature. It is used to simulate the vocalizations made by cats, typically a short, high-pitched sound that cats make to communicate with humans or other cats.
Method Overriding: Method overriding is a feature in object-oriented programming where a subclass provides its own implementation of a method that is already defined in its superclass. This allows the subclass to customize or override the behavior of the inherited method to better suit its specific needs.
Method Resolution Order: Method resolution order (MRO) is a concept in object-oriented programming that determines the order in which a class searches for a method to be executed when it is called on an object. It is a crucial aspect of understanding how inheritance and multiple inheritance work in programming languages like Python.
Multilevel inheritance: Multilevel inheritance occurs when a class is derived from another class, which is itself derived from another class. This forms a chain of inheritance where each level inherits attributes and methods from the preceding level.
Multilevel Inheritance: Multilevel inheritance is a feature of object-oriented programming where a derived class inherits from another derived class, creating a hierarchical chain of inheritance. This allows for the reuse of code and the creation of complex class structures.
Name: In the context of programming, the term 'name' refers to the identifier used to represent a variable, function, or object. It serves as a way to uniquely identify and access these programming elements within a codebase.
Nurse(): The nurse() method is a function within the context of hierarchical inheritance in object-oriented programming. It serves as a mechanism for a derived class to override or extend the behavior of a method inherited from its base class, allowing for specialized functionality to be implemented.
Object-Oriented Programming: Object-Oriented Programming (OOP) is a programming paradigm that focuses on creating objects, which are instances of classes, to represent and manipulate data. It emphasizes the use of encapsulation, inheritance, and polymorphism to create modular, reusable, and maintainable code.
Parent Class: The parent class, also known as the superclass, is the class from which other classes inherit properties and methods. It serves as the foundation for creating more specialized or derived classes, known as child or subclasses.
Pass: The 'pass' statement in Python is a placeholder that does nothing. It is used as a way to indicate that a section of code should do nothing, often used as a temporary measure or when a statement is required syntactically but no action is needed. It is a way to create an empty block of code, allowing the program to continue executing without errors.
Pass-by-object-reference: Pass-by-object-reference is a method of passing arguments to functions where the reference (or address) of the object is passed, not the actual object itself. This means changes made to the object within the function affect the original object outside the function.
Polymorphism: Polymorphism is a fundamental concept in object-oriented programming that allows objects of different classes to be treated as objects of a common superclass. It enables objects to take on multiple forms, allowing them to respond to the same method call in different ways.
Subclass: A subclass is a class that inherits from another class, known as the superclass. Subclasses inherit the attributes and methods of the superclass, allowing them to reuse and extend the functionality of the parent class.
Super(): The 'super()' function is a built-in function in Python that allows a subclass to call a method or access an attribute from its parent or superclass. It is a crucial tool in the context of object-oriented programming, as it enables the reuse of code and the implementation of inheritance hierarchies.
Superclass: A superclass is the parent or base class in an inheritance hierarchy, from which one or more subclasses can inherit attributes and behaviors. It serves as the foundation for creating specialized classes that share common characteristics and functionality.
© 2024 Fiveable Inc. All rights reserved.
AP® and SAT® are trademarks registered by the College Board, which is not affiliated with, and does not endorse this website.