Inheritance
What You'll Learn: In this tutorial, you'll discover how inheritance works in Python, allowing one class to inherit the methods and properties of another class. This helps you create more organized and reusable code.
Creating a Parent Class
A parent class is the class being inherited from, also known as the base class.
Example Code:
class Person:
def __init__(self, fname, lname):
self.firstname = fname
self.lastname = lname
def printname(self):
print(self.firstname, self.lastname)
# Use the Person class to create an object
x = Person("John", "Doe")
x.printname()
Output:
John Doe
Creating a Child Class
A child class is the class that inherits from the parent class, also called the derived class.
Example Code:
class Student(Person):
pass
# Use the Student class to create an object
x = Student("Mike", "Olsen")
x.printname()
Output:
Mike Olsen
Adding the __init__() Function
The __init__() function is called automatically every time the class is used to create a new object.
Example Code:
class Student(Person):
def __init__(self, fname, lname):
Person.__init__(self, fname, lname)
Using the super() Function
The super() function allows the child class to inherit all methods and properties from its parent without explicitly naming the parent class.
Example Code:
class Student(Person):
def __init__(self, fname, lname):
super().__init__(fname, lname)
Adding Properties
You can add additional properties to the child class.
Example Code:
class Student(Person):
def __init__(self, fname, lname, year):
super().__init__(fname, lname)
self.graduationyear = year
x = Student("Mike", "Olsen", 2019)
Adding Methods
You can add new methods to the child class.
Example Code:
class Student(Person):
def __init__(self, fname, lname, year):
super().__init__(fname, lname)
self.graduationyear = year
def welcome(self):
print("Welcome", self.firstname, self.lastname, "to the class of", self.graduationyear)
Try It Yourself: Fun Exercises
- Create Your Own Classes:
- Create a parent class
Animalwith a method that prints the animal's sound. - Create a child class
Dogthat inherits fromAnimaland adds a method to print the dog's breed.
- Create a parent class
- Add Properties and Methods:
- Extend the
Studentclass by adding a new propertymajorand a method to print the student's major.
- Extend the
Summary:
In this Python tutorial, we learned about inheritance, creating parent and child classes, using the __init__() and super() functions, and adding properties and methods. These concepts help you create organized and reusable code. Keep experimenting and have fun with inheritance in Python!