KAHIBARO Bookshelves
Discord Login Register

13.6. Inheritance (basics)

What Is Inheritance?

Inheritance lets you create a new class based on an existing class.

  • The existing class is usually called the parent class, base class, or superclass.
  • The new class is called the child class, subclass, or derived class.

The child class inherits attributes and methods from the parent class, and can:

  • Use them as they are.
  • Change (override) some of them.
  • Add new ones.

This avoids writing the same code again and again when classes are similar.

In Python, you define a child class like this:

class Parent:
    pass
class Child(Parent):
    pass

Here, Child inherits from Parent.

A Simple Inheritance Example

Imagine a general Animal class and more specific animals like Dog and Cat.

class Animal:
    def __init__(self, name):
        self.name = name
    def speak(self):
        print("Some generic animal sound")
class Dog(Animal):
    pass
class Cat(Animal):
    pass
dog = Dog("Buddy")
cat = Cat("Misty")
dog.speak()  # Inherited from Animal
cat.speak()  # Inherited from Animal

Dog and Cat did not define __init__ or speak, but they can still use them because they inherit from Animal.

Adding New Behavior in the Child Class

A child class can have extra attributes or methods that the parent does not have.

class Animal:
    def __init__(self, name):
        self.name = name
    def info(self):
        print(f"I am an animal named {self.name}")
class Dog(Animal):
    def bark(self):
        print("Woof!")
dog = Dog("Rex")
dog.info()   # from Animal
dog.bark()   # only in Dog

The child class keeps everything from the parent and adds more.

Overriding Methods

Sometimes you want a child class to change how a method works.
This is called overriding a method.

class Animal:
    def speak(self):
        print("Some generic animal sound")
class Dog(Animal):
    def speak(self):
        print("Woof!")
class Cat(Animal):
    def speak(self):
        print("Meow!")
dog = Dog()
cat = Cat()
dog.speak()  # Woof!
cat.speak()  # Meow!

Here, Dog and Cat both override speak.
When you call speak on a Dog, you get the Dog version, not the Animal one.

Using `super()` to Reuse Parent Code

Sometimes you want to extend a parent method, not completely replace it.
You can call the parent’s version using super().

This is common with __init__.

class Animal:
    def __init__(self, name):
        self.name = name
class Dog(Animal):
    def __init__(self, name, breed):
        # Call Animal.__init__(self, name)
        super().__init__(name)
        self.breed = breed
dog = Dog("Rex", "Labrador")
print(dog.name)   # from Animal
print(dog.breed)  # from Dog

What happens:

  1. super().__init__(name) runs the parent’s __init__ to set self.name.
  2. Then the child class adds self.breed.

You can also use super() inside other methods:

class Animal:
    def info(self):
        print("I am an animal.")
class Dog(Animal):
    def info(self):
        super().info()        # Call parent version
        print("I am also a dog.")
dog = Dog()
dog.info()
# I am an animal.
# I am also a dog.

Inheritance vs. Just Using Attributes

You might wonder: why not just give every class the same attributes and methods manually?

Without inheritance:

class Dog:
    def __init__(self, name):
        self.name = name
    def speak(self):
        print("Woof!")
class Cat:
    def __init__(self, name):
        self.name = name
    def speak(self):
        print("Meow!")

Here, __init__ is duplicated. If you need to change how names are stored, you must change it in multiple places.

With inheritance:

class Animal:
    def __init__(self, name):
        self.name = name
class Dog(Animal):
    def speak(self):
        print("Woof!")
class Cat(Animal):
    def speak(self):
        print("Meow!")

Now, the shared part (__init__) lives in one place (Animal), and Dog and Cat only define what is different.

“Is-a” Relationship

A helpful rule: use inheritance when the relationship is “is-a”.

  • A Dog is an Animal → inheritance makes sense.
  • A Car is a Vehicle → inheritance can make sense.

But if the relationship is more like “has-a”, you usually do not use inheritance.
For example:

  • A Car has an engine (it doesn’t “is-a” engine).
  • A Person has an address.

Those are usually better handled with attributes (one object containing another), not inheritance.
(This idea—using objects inside other objects—is usually called composition, and can be explored separately.)

Basic Inheritance Example: Shapes

Here is a small example with a parent Shape and two child classes.

class Shape:
    def area(self):
        # Generic shape has no defined area
        return 0
class Rectangle(Shape):
    def __init__(self, width, height):
        self.width = width
        self.height = height
    def area(self):
        # Override parent method
        return self.width * self.height
class Square(Rectangle):
    def __init__(self, side):
        # A square is a rectangle with equal sides
        super().__init__(side, side)
rect = Rectangle(3, 4)
square = Square(5)
print(rect.area())    # 12
print(square.area())  # 25

What this shows:

  • Rectangle and Square both inherit from Shape.
  • Rectangle overrides area.
  • Square reuses the Rectangle __init__ via super().

When (and When Not) to Use Inheritance

Use inheritance when:

  • You have a clear “is-a” relationship.
  • Classes share common behavior that should live in one place.
  • Child classes need to specialize or extend the parent’s behavior.

Be careful with inheritance when:

  • You are only using it to “reuse code” with no real “is-a” meaning.
  • The child class ends up very different from the parent.
  • There are many levels of inheritance that become hard to follow.

In those cases, it may be simpler to use normal attributes (objects containing other objects) instead of inheritance.

Small Practice Ideas

You can try building simple class trees like:

  • Vehicle → Car, Bike
  • Person → Student, Teacher
  • Account → SavingsAccount, CheckingAccount

For each:

  1. Put shared attributes and methods in the parent class.
  2. Add specific behavior in each child class.
  3. Override at least one method in a child class.
  4. Optionally, use super() in a child __init__.

Views: 0

Comments

Please login to add a comment.

Don't have an account? Register now!

Where to Move

Move chapter:

  • ☰ 1. Chapter 1: What Is Programming?
    • ☰ 1.1. What is a computer program?
      • ☰ 1.2. What is Python?
        • ☰ 1.3. Where is Python used?
          • ☰ 1.4. How programming helps solve problems
            • ☰ 1.5. Your first Python program
            • ☰ 2. Chapter 2: Setting Up Python
              • ☰ 2.1. Installing Python (Windows / macOS / Linux)
                • ☰ 2.2. Using Python in the terminal
                  • ☰ 2.3. Using an IDE (IDLE / VS Code)
                    • ☰ 2.4. Running Python scripts
                      • ☰ 2.5. Python interactive mode
                      • ☰ 3. Chapter 3: Variables and Data Types
                        • ☰ 3.1. What is a variable?
                          • ☰ 3.2. Creating variables
                            • ☰ 3.3. Numbers
                              • ☰ 3.4. Test
                                • ☰ 3.5. Boolean values
                                  • ☰ 3.6. Type checking
                                  • ☰ 4. Chapter 4: Basic Operations
                                    • ☰ 4.1. Arithmetic operations
                                      • ☰ 4.2. Working with numbers
                                        • ☰ 4.3. String operations
                                          • ☰ 4.4. Combining text and variables
                                            • ☰ 4.5. Comments in Python
                                            • ☰ 5. Chapter 5: User Input and Output
                                              • ☰ 5.1. Getting input from the user
                                                • ☰ 5.2. Converting input to numbers
                                                  • ☰ 5.3. Formatting output
                                                    • ☰ 5.4. Writing interactive programs
                                                    • ☰ 6. Chapter 6: Conditions
                                                      • ☰ 6.1. Comparison operators
                                                        • ☰ 6.2. Logical operators
                                                          • ☰ 6.3. if, elif, else
                                                            • ☰ 6.4. Nested conditions
                                                              • ☰ 6.5. Common beginner mistakes
                                                              • ☰ 7. Chapter 7: Loops
                                                                • ☰ 7.1. Why loops are useful
                                                                  • ☰ 7.2. for loops
                                                                    • ☰ 7.3. while loops
                                                                      • ☰ 7.4. Loop counters
                                                                        • ☰ 7.5. break and continue
                                                                          • ☰ 7.6. Loop exercises
                                                                          • ☰ 8. Chapter 8: Data Collections
                                                                            • ☰ 8.1. Lists
                                                                              • ☰ 8.2. Tuples
                                                                                • ☰ 8.3. Dictionaries
                                                                                  • ☰ 8.4. Sets (basics)
                                                                                    • ☰ 8.5. Choosing the right data structure
                                                                                    • ☰ 9. Chapter 9: Functions
                                                                                      • ☰ 9.1. Why functions matter
                                                                                        • ☰ 9.2. Defining functions
                                                                                          • ☰ 9.3. Parameters and arguments
                                                                                            • ☰ 9.4. Return values
                                                                                              • ☰ 9.5. Scope (local vs global)
                                                                                                • ☰ 9.6. Reusing code
                                                                                                • ☰ 10. Chapter 10: Working with Files
                                                                                                  • ☰ 10.1. What is a file?
                                                                                                    • ☰ 10.2. Reading text files
                                                                                                      • ☰ 10.3. Writing and appending files
                                                                                                        • ☰ 10.4. File paths
                                                                                                          • ☰ 10.5. Simple file-based programs
                                                                                                          • ☰ 11. Chapter 11: Errors and Debugging
                                                                                                            • ☰ 11.1. Types of errors
                                                                                                              • ☰ 11.2. Reading error messages
                                                                                                                • ☰ 11.3. Common beginner errors
                                                                                                                  • ☰ 11.4. try and except
                                                                                                                    • ☰ 11.5. Debugging strategies
                                                                                                                    • ☰ 12. Chapter 12: Using Python Libraries
                                                                                                                      • ☰ 12.1. What is a library?
                                                                                                                        • ☰ 12.2. Importing modules
                                                                                                                          • ☰ 12.3. Standard libraries
                                                                                                                            • ☰ 12.3.1. math
                                                                                                                              • ☰ 12.3.2. random
                                                                                                                                • ☰ 12.3.3. datetime
                                                                                                                                • ☰ 12.4. Installing external libraries with pip
                                                                                                                                • ☰ 13. Chapter 13: Object-Oriented Programming
                                                                                                                                  • ☰ 13.1. What is object-oriented programming?
                                                                                                                                    • ☰ 13.2. Classes and objects
                                                                                                                                      • ☰ 13.3. The `__init__` method
                                                                                                                                        • ☰ 13.4. Attributes and methods
                                                                                                                                          • ☰ 13.5. Encapsulation
                                                                                                                                            • ☰ 13.6. Inheritance (basics)
                                                                                                                                              • ☰ 13.7. Simple OOP examples
                                                                                                                                              • ☰ 14. Chapter 14: Automation with Python
                                                                                                                                                • ☰ 14.1. What is automation?
                                                                                                                                                  • ☰ 14.2. Automating simple tasks
                                                                                                                                                    • ☰ 14.3. Working with files and folders
                                                                                                                                                      • ☰ 14.4. Automating text processing
                                                                                                                                                        • ☰ 14.5. Scheduling scripts
                                                                                                                                                          • ☰ 14.6. Practical automation examples
                                                                                                                                                          • ☰ 15. Chapter 15: Web Development with Python
                                                                                                                                                            • ☰ 15.1. How the web works (basic overview)
                                                                                                                                                              • ☰ 15.2. Introduction to Flask
                                                                                                                                                                • ☰ 15.3. Creating a simple web server
                                                                                                                                                                  • ☰ 15.4. Routing and templates
                                                                                                                                                                    • ☰ 15.5. Handling user input (forms)
                                                                                                                                                                      • ☰ 15.6. Very basic APIs
                                                                                                                                                                      • ☰ 16. Chapter 16: Data Science with Python
                                                                                                                                                                        • ☰ 16.1. What is data science?
                                                                                                                                                                          • ☰ 16.2. Working with data
                                                                                                                                                                            • ☰ 16.3. Introduction to NumPy
                                                                                                                                                                              • ☰ 16.4. Introduction to pandas
                                                                                                                                                                                • ☰ 16.5. Data visualization with matplotlib
                                                                                                                                                                                  • ☰ 16.6. Simple data analysis examples
                                                                                                                                                                                  • ☰ 17. Chapter 17: Mini Projects
                                                                                                                                                                                    • ☰ 17.1. Number guessing game
                                                                                                                                                                                      • ☰ 17.2. Simple calculator
                                                                                                                                                                                        • ☰ 17.3. To-do list
                                                                                                                                                                                          • ☰ 17.4. Password generator
                                                                                                                                                                                            • ☰ 17.5. Quiz application
                                                                                                                                                                                              • ☰ 17.6. Small web or data project
                                                                                                                                                                                              • ☰ 18. Chapter 18: Next Steps
                                                                                                                                                                                                • ☰ 18.1. How to practice Python
                                                                                                                                                                                                  • ☰ 18.2. Writing clean and readable code
                                                                                                                                                                                                    • ☰ 18.3. Choosing a specialization
                                                                                                                                                                                                      • ☰ 18.3.1. Web development
                                                                                                                                                                                                        • ☰ 18.3.2. Data science
                                                                                                                                                                                                          • ☰ 18.3.3. Automation
                                                                                                                                                                                                            • ☰ 18.3.4. Software development
                                                                                                                                                                                                            • ☰ 18.4. Learning resources and communities
                                                                                                                                                                                                            • ☰ 19. Appendix
                                                                                                                                                                                                              • ☰ 19.1. Python syntax cheat sheet
                                                                                                                                                                                                                • ☰ 19.2. Common errors and solutions
                                                                                                                                                                                                                  • ☰ 19.3. Glossary of terms