Lesson 77 +10 XP

Inheritance

Inheritance

Inheritance lets a class reuse code from another class. The child gets everything the parent has, then adds its own.

Parent and child

  • Parent class (base): the one being inherited from.
  • Child class (derived): the one doing the inheriting.
class Person:  # parent
    def __init__(self, fname, lname):
        self.firstname = fname
        self.lastname = lname

    def printname(self):
        print(self.firstname, self.lastname)

class Student(Person):  # child
    pass

x = Student("Mike", "Olsen")
x.printname()  # Mike Olsen

Pass in the class name

The parent goes in parentheses: class Student(Person):.

The child inherits everything

Student automatically gets __init__ and printname from Person.

Add your own __init__

When the child adds its own __init__, it must call the parent's:

class Student(Person):
    def __init__(self, fname, lname, year):
        super().__init__(fname, lname)
        self.graduationyear = year

super()

super() refers to the parent class. super().__init__(...) runs the parent's setup.

Override methods

The child can redefine a method to change its behavior:

class Student(Person):
    def printname(self):
        print("Student:", self.firstname, self.lastname)

Add new methods

The child adds brand-new methods freely.

TL;DR

  • class Child(Parent): inherits.
  • The child gets all parent methods and attributes.
  • super().__init__(...) calls the parent constructor.
  • Override methods by redefining them; add new ones freely.