HexLibraryHexLibrary
</> HexCodeSign inSign up
PythonJavaScriptTypeScriptCC++JavaPHPGoRustRubyBashSQLLuaPerlCOBOLPascalDelphiFortranDartSwiftC#JuliaGroovyRElixirHaskellKotlinScalaClassic ASPClipperMS-DOS
LESSONS
Introduction to Python: Print and RepeatVariablesData Types & NumbersStringsListsConditions (if / elif / else)Loops (for / while)FunctionsOperatorsDictionariesTuples & SetsError Handling (try / except)Classes (Object-Oriented)File OperationsComments & IndentationBooleans (True / False)Lambda & map / filterModules (import)InheritanceVariable Scope
REFERENCE
📖 Overview
🖥️ Output & Input
🔢 Numbers & Math
✍️ String
📋 List
🗂️ Dictionary & Set
🔁 Condition & Loop
🧩 Function
📁 File & Error
🔄 Type & Conversion
Python›Inheritance

Inheritance

A class inheriting attributes and methods from another class; method overriding.

Simple enough for a 5-year-old to understand

Deriving from a class

Inheritance is passing an existing class's features on to a new class. You don't rewrite them, you inherit them.

Animal → Dog
1
class Animal:
The parent (super) class.
DefinitionThe parent (super) class.
2
def __init__(self, name):
Constructor.
FunctionConstructor.
3
self.name = name
The name attribute.
VariableThe name attribute.
4
class Dog(Animal):
A subclass derived from Animal.
DefinitionA subclass derived from Animal.
5
def sound(self):
Method specific to the dog.
FunctionMethod specific to the dog.
6
return f"{self.name}: Woof!"
Uses the inherited name.
FunctionUses the inherited name.
7
k = Dog("Rex")
Dog object (name comes from Animal).
CodeDog object (name comes from Animal).
8
print(k.sound())
Rex: Woof!
Output / InputRex: Woof!
DefinitionFunctionVariableCodeOutput / Input
💡 Hint: Dog(Animal) → means "Dog inherits everything from Animal".

🎯 Exercise & Practice

Test what you've learned — answer, write code, check instantly. (1 left)

1.What does class Dog(Animal): mean?

About this topic

Inheritance is when a class inherits the properties of another class. You write an Animal class and derive Cat and Dog from it; both take Animal's common behaviors and add their own differences on top. You save yourself from writing the same code twice.

The true power of inheritance is when the derived class OVERRIDES a method. It changes the generic make-sound method in the Animal class so that a Cat meows and a Dog barks. The rest of the program can just say "this is an Animal" and when it calls it, the correct sound comes out — this is called polymorphism.

Inheritance is powerful, but harmful when exaggerated. Deep inheritance chains — A to B, B to C, C to D — make the code untraceable. Modern advice is to use composition as much as possible instead of inheritance: putting another object inside a class.

What you will learn

  • inheriting from a class
  • overriding methods
  • calling the parent class's method with super
  • what polymorphism provides in practice
  • checking types with isinstance
  • when composition is better than inheritance

When to use?

Use inheritance for classes that have a true "is-a" relationship between them: a cat is an animal, a square is a shape. Common behavior goes to the parent class, differences go to child classes.

If the relationship is not "is-a" but "has-a", inheritance is wrong. A car has an engine, a car is NOT an engine; in that case, you need to keep the engine as an object inside the car.

Common mistakes

Wrong

class Animal:
    def __init__(self, name):
        self.name = name

class Cat(Animal):
    def __init__(self, name, color):
        self.color = color

c = Cat("Tabby", "gray")
print(c.name)

Since the child class's constructor does not call the parent class's constructor, name is never assigned; the result is "AttributeError: 'Cat' object has no attribute 'name'". You need to call the parent constructor with super.

Correct

class Cat(Animal):
    def __init__(self, name, color):
        super().__init__(name)
        self.color = color

Wrong

class Cat(Animal):
    def speak(self):
        Animal.speak(self)
        print("meow")

Calling the parent class by its name works but is fragile: if the parent class name changes or if there is multiple inheritance, the wrong class gets called. Using super automatically finds the correct class.

Correct

class Cat(Animal):
    def speak(self):
        super().speak()
        print("meow")

Wrong

if type(animal) == Cat:
    animal.meow()

Comparing with type rejects a class derived from Cat; it defeats the purpose of inheritance. Using isinstance also accepts child classes and remains flexible.

Correct

if isinstance(animal, Cat):
    animal.meow()

Frequently asked questions

what exactly does super do?

It allows you to access the parent class's method. Most commonly used in the constructor: the child class first does the parent class's initialization work, then assigns its own extra fields. Using super instead of typing the parent class name protects the code from breaking when the class hierarchy changes.

Does Python support multiple inheritance?

Yes, a class can be derived from more than one class. However, if the same method exists in multiple parent classes, which one is called is resolved according to a specific order, and this can get complicated. It is a common recommendation to use multiple inheritance only for small, behavior-adding classes.

Inheritance or composition?

The rule is: if the relationship is "is-a", use inheritance, if it is "has-a", use composition. When in doubt, choose composition; keeping an object internally is more flexible and easier to test than entering an inheritance chain. The common tendency of experienced developers is toward composition.

Summary

Inheritance allows you to gather common behavior in the parent class and define differences in child classes; the parent class is accessed with super, and polymorphism is established through method overriding.

HexLibraryHexLibrary

Learn programming more clearly. Every command is explained line by line with colors, reinforced with runnable exercises, test your code instantly — all in one place, free.

Learn

  • Home
  • Languages & Lessons
  • HexCode

Company

  • About
  • Contact

Legal

  • Privacy Policy
  • Terms of Use

Other Projects

  • HexToolz
  • Free Service Manuals
© 2026 HexLibrary · The clearest way to learn code