Lesson 37 of 4093%
(Progress persistence is disabled until Phase 9)
Python
Intermediate
Inheritance
Create classes that inherit properties from other classes.
Inheritance
What You’ll Learn
Inheritance allows us to define a class that inherits all the methods and properties from another class.
Parent and Child Classes
- Parent class is the class being inherited from, also called base class.
- Child class is the class that inherits from another class, also called derived class.
# Parent Class
class Animal:
def __init__(self, name):
self.name = name
def eat(self):
print(f"{self.name} is eating.")
# Child Class inherits from Animal
class Dog(Animal):
def bark(self):
print("Woof!")
my_dog = Dog("Buddy")
my_dog.eat() # Inherited from Animal
my_dog.bark() # Specific to Dog
The super() Function
Python also has a super() function that will make the child class inherit all the methods and properties from its parent.
class Dog(Animal):
def __init__(self, name, breed):
super().__init__(name) # Calls the Animal __init__
self.breed = breed