Basic Inheritance
Part of the Object Oriented Programming section of Coddy's Python journey — lesson 17 of 64.
Inheritance allows a class to inherit attributes and methods from another class, creating a parent-child relationship.
Here is an example of a parent class:
class Animal:
def __init__(self, name):
self.name = name
def info(self):
print(f"I am {self.name}, an animal")Create a child class that inherits from the parent:
class Dog(Animal):
pass # Inherits everything from AnimalThe syntax class Dog(Animal): means Dog inherits from Animal. Put the parent class name in parentheses.
Create objects from both classes:
generic_animal = Animal("Creature")
buddy = Dog("Buddy")Use the inherited methods:
generic_animal.info()
buddy.info()Output:
I am Creature, an animal
I am Buddy, an animalEven though Dog doesn't define __init__ or info, it automatically gets them from Animal.
You can add new methods to the child class:
class Dog(Animal):
def bark(self):
print(f"{self.name} says Woof!")
buddy = Dog("Buddy")
buddy.info() # Inherited method
buddy.bark() # New methodOutput:
I am Buddy, an animal
Buddy says Woof!Key Point: Child classes inherit all attributes and methods from their parent class. Use class Child(Parent): syntax to create inheritance. This helps you reuse code and create logical class hierarchies.
Challenge
Mediumvehicle.py: Contains the parentVehicleclasscar.py: Contains theCarclass that inherits fromVehicledriver.py: Main file to test your implementation
Each file contains detailed TODO comments to guide you through the implementation. You'll need to:
- Complete the
Vehicleclass with make and model attributes - Implement proper class inheritance in the
Carclass - Set up the correct import statements between files
- Create and test objects in the driver file
Follow the TODO comments carefully as they provide step-by-step guidance to the solution.
Cheat sheet
Inheritance allows a class to inherit attributes and methods from another class using class Child(Parent): syntax:
class Animal:
def __init__(self, name):
self.name = name
def info(self):
print(f"I am {self.name}, an animal")
class Dog(Animal):
pass # Inherits everything from AnimalChild classes automatically inherit all parent methods and attributes:
buddy = Dog("Buddy")
buddy.info() # Uses inherited method
# Output: I am Buddy, an animalAdd new methods to child classes while keeping inherited functionality:
class Dog(Animal):
def bark(self):
print(f"{self.name} says Woof!")
buddy = Dog("Buddy")
buddy.info() # Inherited method
buddy.bark() # New methodTry it yourself
# TODO: Import the Vehicle class from vehicle.py
# TODO: Import the Car class from car.py
# TODO: Create a Vehicle object with make "Toyota" and model "Corolla"
vehicle = None
# TODO: Create a Car object with make "Honda" and model "Civic"
car = None
# TODO: Call display_info() method on the vehicle object
# Expected output: "Vehicle: Toyota Corolla"
# TODO: Call display_info() method on the car object
# Expected output: "Vehicle: Honda Civic"
# Note: Car inherits display_info from Vehicle without modificationThis lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Object Oriented Programming
1Fundamentals of OOP
External FilesIntroduction to OOPClasses vs ObjectsThe self ParameterMethodsAttributesConstructor Method (__init__)Recap - Simple Calculator4Inheritance
Basic InheritanceThe super() FunctionMethod OverridingMultiple InheritanceMethod Resolution OrderRecap - Employee Hierarchy7Special Methods
Magic Methods IntroductionOperator OverloadingContainer Magic MethodsRecap - Custom List10Design Patterns Part 1
Intro to design patternSingleton PatternFactory PatternObserver PatternStrategy Pattern2Decorators
Introduction to DecoratorsProperty DecoratorStatic Method DecoratorClass Method Decorator5Polymorphism
Method Overriding RevisitedDuck TypingAbstract Classes and MethodsInterface DesignRecap - Shape Calculator8Advanced OOP Concepts
Composition vs InheritanceMixinsStatic and Class MethodsClass DecoratorsContext Managers3Class Properties
Instance vs Class VariablesProperty DecoratorsPrivate AttributesRecap - Bank Account Manager6Encapsulation
Public, Protected, Private MemAccess ModifiersInformation HidingProperty Decorators AdvancedRecap - Student Records System12Project: Library Management
Project OverviewBook and User Classes