PedroGeoGISdev
  • Home
  • Linux OS
    • Linux: concepts
    • Linux: basic concepts
    • Linux: Bash
    • Linux: su and sudo
    • Linux: pipes
    • Linux: File System
    • Linux: Virtual Machines

    • Linux: distros
    • Linux Distros: Ubuntu
    • Linux Distros: Mint
    • Linux Distros: Debian
    • Linux Distros: openSuse
    • Linux Distros: Manjaro
    • Linux Distros: Red Hat Enterprise

    • Linux: laboratories
    • Linux Lab#LI01-1: Choose Linux
    • Linux Lab#LI01-2: Install at least three distributions
    • Linux Lab#LI01-3: Adjust user permissions
    • Linux Lab#LI02-1: Export env user with grep and pipe
    • Linux Lab#LI03-1: Manage users and groups
    • Linux Lab#LI03-2: Manage files
    • Linux Lab#LI03-3: Manage software
    • Linux Lab#LI03-4: Manage hardware
    • Linux Lab#LI04-1: Bash scripting, qtool
    • Linux Lab#LI04-2: Bash scripts as terminal tool
    • Linux Lab#LI04-3: Distribute the terminal app

    • Linux readings
    • Linux Resources
  • DevOps
    • What is DevOps
    • DevOps: Introduction
    • DevOps: Agile and Microservices
    • Infrastructure as code (IaC)
    • Immutable Infrastructure
    • Software Lifecycle

    • Documentation
    • How to document: Quarto and Obsidian

    • Network protocols
    • Network: Basics
    • Network: Client-server
    • Network Protocols
    • Network: DNS
    • Network: API Rest
    • Network: gRPC
    • Network: Websocket
    • Network: SMTP
    • Network: Ping
    • Network: UDP
    • Network: webhook
    • Network: SOAP
    • Network: graphQL

    • Version Control
    • Git
    • GitHub
    • Idea and GitHub 2023
    • Git and GitHub 2023 CLI

    • IDEs
    • IDE: Visual Code
    • IDE: IntellJIdea

    • DevOps tools
    • Amazon Web Services AWS
    • Docker
    • Jenkins pipelines
    • Kubernetes k8s
    • Digital Ocean
    • Nagios
    • Ansible

    • DevOps Laboratories
    • Lab 1: chat App
    • Lab 2: Spring Boot AWS AEB manually
    • Lab 3: Spring Boot and AWS S3 publisher
    • Lab 4: Spring Boot Docker/Jenkins
    • Lab 5: k8s on Digital Ocean
    • Lab 6: Spring Boot AWS codecommit

    • DevOps readings
    • DevOps Resources
  • MarkUp
    • MarkUp Languages
    • Introduction Markup
    • HTML Markup
    • Markdown Markup
    • Markdown and HTML working together, good idea?

    • Quarto Markdown
    • Quarto Markdown: basics
    • Quarto Markdown: creating
    • Quarto Markdown: publishing
    • Quarto Markdown: code & data
    • Quarto Markdown: api rest call
    • Quarto Markdown: OJS Cells
    • Quarto Markdown: cheat-sheet

    • Styling: CSS
    • Cascade Style Sheet
    • Cascade Style Sheet: Box Model and Containers
    • CSS: W3.css

    • MarkUp Languages Laboratories
    • Lab#MD01-1: Create and publish by Quarto

    • MarkUp Languages readings
    • MarkUp Languages Resources
  • Java SE
    • What is Java SE
    • Java Standard Edition: Basics
    • Java Standard Edition: Principles
    • Java MOOC Helsinki
    • Java MOOC Helsinki Syllabus

    • Java Create Project
    • Java SE: Maven
    • Java SE: Create Maven Project
    • Java SE: Project push GitHub
    • Java SE: JUnit and TDD

    • Java Concepts
    • Java SE: Class and Objects
    • Java SE: Scope
    • Java SE: static modifier
    • Java SE: Coupling and DDD
    • Java SE: Packages
    • Java SE: Abstract/Interface
    • Java SE: Java 8

    • Java Principles
    • Java SE: Encapsulation
    • Java SE: Abstraction
    • Java SE: Inherence
    • Java SE: Polymorphism

    • Java Design Patterns
    • Java Patterns: UML
    • Java Patterns: Types
    • Singleton
    • Factory
    • Abstract Factory
    • Builder
    • Facade
    • Bridge
    • Decorator
    • Composite
    • Observer
    • Strategy
    • State
    • Commander

    • Java SE Laboratories
    • Lab#SE00-1: Maven Person
    • Lab#SE00-2: Maven Clinic
    • Lab#SE00-3: Library Model
    • Lab#SE00-4: Abstract/Interface Human
    • Lab#SE01-1: Maven/Gradle Person and Account
    • Lab#SE01-2: Maven/Gradle Person and Account stored in JSON
    • Lab#SE02-1: Movie/Review, Model
    • Lab#SE02-2: Movie/Review, CRUD Operations
    • Lab#SE02-3: Movie/Review, factory
    • Lab#SE02-4: Movie/Review, interactivity and coupling
    • Lab#SE02-5: Movie/Review, simulate interactivity by console
    • Lab#SE03-1: Library/Book, Core-Model
    • Lab#SE03-2: Library/Book, Sprint Zero
    • Lab#SE03-3: Library/Book, Expand Model
    • Lab#SE04-1: healthyFood Restaurant, Core Model

    • Java SE readings
    • Java SE Resources
  • Python
    • Python Basics
    • Python: Basic Concepts
    • Python: Numbers
    • Python: Strings
    • Python: Conditionals
    • Python: Lists and Loops
    • Python: Nested Loops
    • Python: Tuples
    • Python: Sets
    • Python: Dictionaries
    • Python: Functions
    • Python: Higher-order Functions
    • Python: Variable Scope
    • Python: Variable Assigment
    • Python: None keyword in Python
    • Python: Object Oriented Programming (OOP)
    • Python: Inheritance and Polymorphism
    • Python: Encapsulation
    • Python: Abstraction
    • Python: Cheat-Sheets
  • JavaScript
    • JavaScript Basics
    • JavaScript: Basic Concepts
    • JavaScript: Tips

    • React Framework

    • ReactJS: Principles
    • React JS: Introduction
    • React JS: render virtual DOM
    • React JS: Create a React project
    • React JS: Components
    • React JS: JSX
    • React JS: props and state

    • JavaScript: web scripting
    • JavaScript: basics
    • JavaScript: functions
    • JavaScript: objects
    • JavaScript: variables
    • JavaScript: flux control

    • ES6: ECMAScript 6
    • React JS ES6: arrow functions
    • React JS ES6: import modules
    • React JS ES6: array, data and key
    • React JS ES6: destructuring
    • React JS ES6: spread operator

    • ReacJS 18: Hooks
    • React JS: Rules of Hooks
    • ReactJS: useState
    • React JS: useReducer
    • React JS: useRef
    • React JS: useEffect
    • React JS: useContext
    • ReactJS: useMemo
    • ReactJS: custom hooks

    • ReactJS: Designing an App
    • React JS App: async
    • React JS App: events
    • React JS App: router
    • React JS App: conditional render
    • React JS App: styling

    • React JS: Laboratories
    • Lab#RE01-1: API Rest Axios
    • Lab#RE02-1: Router & Hooks
    • Lab#RE03-1: to-do app
    • Lab#RE03-2: HighCharts
    • Lab#RE03-3: API Rest Mono
    • Lab#RE03-4: API Rest Domains
    • Lab#RE03-5: data management
    • Lab#RE04-1: todo & server
    • Lab#RE04-2: Spring Boot & ReactJS
    • Lab#RE05-1: chat & websockets
    • Lab#RE05-2: chat: backend
    • Lab#RE05-3: chat & AWS
    • Lab#RE05-4: chat: test ws AWS
    • Lab#RE05-5: chat & front
    • Lab#RE05-6: chat & ws: front
    • Lab#RE06-1: healthyFood Restaurant
    • Lab#RE06-1-PR: create a pull request
    • Lab#RE07-1: traffic lights simulation

    • React JS readings
    • ReactJS Resources
  • Backend
    • Spring Legacy
    • Spring Framework
    • Spring MVC
    • Springs Servlets

    • Spring Boot Basics
    • Spring Boot: fundamentals
    • Spring Boot: create a Project
    • Spring Boot: H2 DB and Thymeleaf
    • Spring Boot: cycle

    • Spring Boot Concepts
    • Spring Boot: Dependency Injection
    • Spring Boot: Annotations
    • Spring Boot: Controller
    • Spring Boot: View
    • Spring Boot: Thymeleaf
    • Spring Boot: Vaadin Flow
    • Spring Boot: Vaadin Hilla
    • Spring Boot: Model
    • Spring Boot: Rest
    • Spring Boot: Data & DB
    • Spring Boot: JPA & DI
    • Spring Boot: JPA Mappings
    • Spring Boot: JPA Relationships
    • Spring Boot: JPA Queries
    • Spring Boot: JPA Inherence
    • Spring Boot: Scaling

    • Spring Boot Laboratories
    • Lab#SB00-1: Library UML
    • Lab#SB00-2: CRUD User
    • Lab#SB00-3: LibraryManagement
    • Lab#SB00-4: API Rest
    • Lab#SB00-5: Rest & JPA-H2
    • Lab#SB00-6: Rest & MongoDB
    • Lab#SB00-7: Styling
    • Lab#SB01-1: DataBase
    • Lab#SB02-1: JPA Relationships
    • Lab#SB03-1: APIs & cloud
    • Lab#SB04-1: JPA Inherence
    • Lab#SB05-1: API Rest
    • Lab#SB06-1: employeeCourse
    • Lab#SB07-1: monitor Book
    • Lab#SB08-1: Restaurant UML
    • Lab#SB08-2: Vaadin
    • Lab#SB08-3: H2 and API Rest
    • Lab#SB08-4: JPA
    • Lab#SB08-5: Test API Rest
    • Lab#SB09-1: SpringIO Conference

    • Spring Boot readings
    • Spring Boot Resources
  • Learning
    • Vocabulary
    • General Vocabulary
    • SCRUM Vocabulary
    • DevOps Vocabulary
    • Java SE Vocabulay
    • Spring Boot Vocabulary
    • DataBase Vocabulary
    • ReactJS Vocabulary
    • Web Vocabulary

    • Learning
    • Useful Questions
    • Learning: tips
    • Writing
    • Taking Notes
    • Comments
    • Document
    • Auto-Evaluate

    • Books & Articles
    • Books
    • Articles

    • What is SCRUM
    • SCRUM Agile Methodology
    • Agile Manifesto & Values
    • SCRUM Guide

    • Scrum Steps
    • Meetings, Impediments and Iterations
    • User stories, Tasks and Habits
    • Delivering Value & Communication
    • ScrumMaster, how it works
    • Mindset, the key to everything
    • Product Owner, how it works
    • Managing Time & Mind
    • Team & the Specialist
    • Albertus’ Dilemma
    • Before SCRUM
    • Team Dynamics
    • Emotions and Thoughts
    • Decision Making and Intuition
    • Beyond SCRUM
    • Balances, atmosphere and tools

    • Resources
    • SCRUM Resources
  • QGIS
    • QGIS basics
    • QGIS: basic concepts

    • QGIS laboratories
    • QGIS Laboratory 1: Introduction to Open Source GIS
  • ArcGIS Pro
    • ArcGIS Pro basics
    • ArcGIS Pro: basic concepts

    • ArcGIS Pro laboratories
    • ArcGIS Pro Laboratory 1: Getting Started
  • Bookmarks
    • Online Resources
    • Online Resources
  • About
    • About me and this site
    • About me
    • About this site
    • About images credit
  • Maps
  • Featured Projects
    • ✈️ Flight tracker
    • 🧑 People tracker
    • 🚗 Renting Car
    • Email
    • GitHub
    • LinkedIn
  1. Python Basics
  2. Python: Inheritance and Polymorphism
  • Python

  • Python Basics
    • Python: Basic Concepts
    • Python: Numbers
    • Python: Strings
    • Python: Conditionals
    • Python: Lists and Loops
    • Python: Nested Loops
    • Python: Tuples
    • Python: Sets
    • Python: Dictionaries
    • Python: Functions
    • Python: Higher-order Functions
    • Python: Variable Scope
    • Python: Variable Assigment
    • Python: None keyword in Python
    • Python: Object Oriented Programming (OOP)
    • Python: Inheritance and Polymorphism
    • Python: Encapsulation
    • Python: Abstraction
    • Python: Cheat-Sheets

On this page

  • 1 Overview
  • 2 Main Aspects of Inheritance in Python
    • 2.1 Simple Example
    • 2.2 More Inheritance Examples
  • 3 Multiple Class Inheritance
  • 4 The super() Function
  • 5 Method Overriding
  • 6 Polymorphism
  • 7 Example
  • 8 More realistic example
  • Edit this page
  • View source
  • Report an issue
  1. Python Basics
  2. Python: Inheritance and Polymorphism

Python: Inheritance and Polymorphism

Python Inheritance and Polymorphism

python
inheritance
polymorphism
Python Inheritance
Author

Isaac Boixaderas

Published

Sunday, June 1, 2025

Modified

Sunday, October 12, 2025

1 Overview

📘 Inheritance

In Python, Inheritance is a programming paradigm based on the concept of “objects”, which can contain data in the form of fields (often known as attributes or properties), and code, in the form of procedures (often known as methods). Inheritance in Python is a key feature of object-oriented programming that allows a new class (child/subclass) to inherit attributes and methods from an existing class (parent/superclass). This mechanism promotes code reuse and models real-world hierarchical relationships. In other words, building on existing classes’ code.

2 Main Aspects of Inheritance in Python

  • Basic Concept: A child class inherits the behaviors (methods) and properties (attributes) of a parent class. The child class can use these inherited features directly or override them with its own implementations. This represents an “is-a” relationship (e.g., a Dog “is-a” Animal).
  • Syntax: The child class is defined by placing the parent class name in parentheses after the child class name:
class ParentClass:
    # attributes and methods

class ChildClass(ParentClass):
    # additional or overridden attributes and methods

This tells Python the ChildClass inherits from ParentClass.

  • Method Overriding: The child class can provide a new definition for a method inherited from the parent, changing its behavior while keeping the same method name. This is essential for customizing behavior.
  • Using super(): The super() function allows a child class to call methods (like __init__) from its parent class, enabling proper initialization or method extension.
  • Types of Inheritance: Python supports several inheritance types:
    • Single Inheritance: One child, one parent.
    • Multiple Inheritance: One child, multiple parents.
    • Multilevel Inheritance: Chain of inheritance across multiple levels.
    • Hierarchical Inheritance: Multiple children inheriting from one parent.
  • Advantages:
    • Reuse existing code without duplication.
    • Organize related classes into hierarchies.
    • Easy maintenance and extensibility of code.
    • Polymorphism: Child classes can be treated as instances of their parent class, enabling flexible code.

2.1 Simple Example

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

    def info(self):
        print("Animal name:", self.name)

class Dog(Animal):
    def sound(self):
        print(self.name, "barks")

d = Dog("Buddy")
d.info()   # inherited method
d.sound()  # child method

Output:

Animal name: Buddy
Buddy barks

This shows the child class Dog inheriting info() from Animal and adding its own sound() method.


2.2 More Inheritance Examples

class Vehicle:
    # Generic vehicle class
    def __init__(self, brand):
        self.brand = brand

    def has_wheels(self):
        return True


class Car(Vehicle):
    # Car class inherits from Vehicle
    def vehicle_type(self):
        return "Car"
# Superclass (Vehicle) functions can be called
# e.g. __init__() is inherited
c = Car("Tesla")

print(c.vehicle_type())
Car
print(c.has_wheels())
True

3 Multiple Class Inheritance

class Electric:
    # Generic class for electric devices

    def power_source(self):
        return "Electricity"


class ElectricCar(Car, Electric):  # Multiple Inheritance
    pass

ec = ElectricCar("Tesla")

print(ec.vehicle_type())
Car
print(ec.power_source())
Electricity
print(ec.has_wheels())
True

4 The super() Function

  • Call method from parent class.
class Vehicle:

    def __init__(self, brand, wheels):
        self.brand = brand
        self.wheels = wheels


class Car(Vehicle):

    def __init__(self, brand, wheels, doors):
        # Call the parent constructor for reusing logic
        super().__init__(brand, wheels)
        # Add new attributes
        self.doors = doors

c = Car("Tesla", 4, 5)

print(c.wheels)
4
print(c.doors)
5

5 Method Overriding

  • Modify or extend inherited behavior.

class Vehicle:

    def __init__(self, brand, wheels):
        self.brand = brand
        self.wheels = wheels

    def description(self):
        print(f"A mode of transport on {self.wheels} wheels.")


class Car(Vehicle):

    def __init__(self, brand, wheels, doors):
        super().__init__(brand, wheels)
        self.doors = doors

    def description(self):
        # Override parent's method behavior
        print(f"A personal mode of transport on {self.wheels} wheels.")

c = Car("Tesla", 4, 5)
bike = Vehicle("Brompton", 2)

c.description()
A personal mode of transport on 4 wheels.
bike.description()
A mode of transport on 2 wheels.

  • A Car object is both of type Vehicle and Car:
c = Car("Tesla", 4, 5)

print(isinstance(c, Vehicle))
True
print(isinstance(c, Car))
True

6 Polymorphism

  • Polymorphism is an object-oriented programming concept.
  • Refers to the ability of a variable, function, or object to take on multiple forms.
  • Class objects with a common parent class may have functions with the same name, but with different behaviors.

class Vehicle:

    def description(self):
        print("Generic Vehicle")


class Car(Vehicle):

    def description(self):
        print("Four-wheeled Vehicle")


class Bike(Vehicle):

    def description(self):
        print("Two-wheeled Vehicle")

  • All instances have a description() method.
c = Car()
c.description()
Four-wheeled Vehicle
b = Bike()
b.description()
Two-wheeled Vehicle

7 Example

Drawing the shape: O
Area: 78.54
Drawing the shape: ▭
Area: 24

8 More realistic example

HR program to track employees in a company.

class Worker:
    def __init__(self, id_card, phone_num, address, bank_iban):
        self.id_card = id_card
        self.phone_num = phone_num
        self.address = address
        self.bank_iban = bank_iban

    @abstractmethod
    def report_work(self):
        pass

    @abstractmethod
    def calculate_monthly_salary(self):
        pass

    def get_contact_info(self):
        return f"Phone: {self.phone_num}, Address: {self.address}"

    def get_payment_details(self):
        return f"IBAN: {self.bank_iban}, Address: {self.address}"

    def change_bank_iban(self, new_iban, signed_certificate):
        # Check valid signed certificate and, if valid, change IBAN
        ...

class Employee(Worker):
    def __init__(self, id_card, phone_num, address,
                 bank_iban, year_salary):
        super().__init__(id_card, phone_num, address, bank_iban)
        self.year_salary = year_salary

    def report_work(self):
        return "Employee reporting: I've worked 8 hours today."

    def calculate_monthy_salary(self):
        # Consider gross year salary, calculate monthly,
        # subtract SS and IRPF, etc.
        ...

def Executive(Employee):
    def __init__(self, id_card, phone_num, address,
                 bank_iban, year_salary, incentive=None):
        super().__init__(id_card, phone_num, address,
                         bank_iban, year_salary)
        self.incentive = incentive
        self.tasks_completed = []

    def report_work(self):
        return "Executive reporting: I've completed objectives X, Y."

    def calculate_monthly_salary(self):
        fix_salary = super().calculate_monthly_salary()
        # Add incentives
        ...

class Freelancer(Worker):
    def __init__(self, id_card, phone_num, address,
                 bank_iban, hourly_rate):
        super().__init__(id_card, phone_num, address, bank_iban)
        self.hourly_rate = hourly_rate

    def report_work(self):
        return "Freelancer reporting: I've worked 4 hours today."

    def calculate_monthy_salary(self):
        # Consider hourly_rate, hours worked this month, etc.
        ...

class Contractor(Worker):
    def __init__(self, id_card, phone_num, address, bank_iban, contract_fee):
        super().__init__(id_card, phone_num, address, bank_iban)
        self.contract_fee = contract_fee

    def report_work(self):
        return "Contractor reporting: Project completed today."

    def calculate_monthy_salary(self):
        # Consider contract_fee, completion of the project, etc.
        ...

def PaymentSystem():

    def process_payroll(workers):
        """
        Process payroll for a list of workers, regardless of their
        specific type. This function uses polymorphism to call each
        worker's own salary calculation method.
        """
        for worker in workers:
            print(f"Processing payroll for {worker.id_card}")
            salary = worker.calculate_monthly_salary()
            print(f"Salary: {salary}")
            payment_details = worker.get_payment_details()
            print(f"Payment will be transferred to {payment_details}\n")
            status = pay_monthly_salary(salary, payment_details)

            if status:
                print(f"{salary}€ correctly paid to {worker.id_card}")
            else:
                print(f"Payment error: {worker.id_card}.")
Back to top
Python: Object Oriented Programming (OOP)
Python: Encapsulation

License: CC0 1.0 Universal

Per aspera, ad astra

  • Edit this page
  • View source
  • Report an issue