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:

python
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:

python
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:

python
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:

python
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:

python
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:

python
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

  1. Create Your Own Classes:
    • Create a parent class Animal with a method that prints the animal's sound.
    • Create a child class Dog that inherits from Animal and adds a method to print the dog's breed.
  2. Add Properties and Methods:
    • Extend the Student class by adding a new property major and a method to print the student's major.

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!