Loading lesson path
Overview
Inheritance allows us to define a class that inherits all the methods and properties from another class. 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.
Any class can be a parent class, so the syntax is the same as creating any other class:
Person, with firstname and lastname properties, and a printname method: 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, and then execute the printname method:
Formula
x = Person("John", "Doe")x.printname()
To create a class that inherits the functionality from another class, send the parent class as a parameter when creating the child class:
Student, which will inherit the properties and methods from the
class Student(Person): pass
Use the pass keyword when you do not want to add any other properties or methods to the class. Now the Student class has the same properties and methods as the Person class.
Student class to create an object, and then execute the printname method:
Formula
x = Student("Mike", "Olsen")x.printname() Add the init() Function So far we have created a child class that inherits the properties and methods from its parent.
init() function to the child class (instead of the pass keyword).
init() function is called automatically every time the class is being used to create a new object.
init() function to the
class Student(Person):
def __init__(self, fname, lname):#add properties etc.
init() function, the child class will no longer inherit the parent's init() function.
init() function overrides the inheritance of the parent's init() function.
init() function, add a call to the parent's init() function:
class Student(Person):
def __init__(self, fname, lname):
Person.__init__(self, fname, lname)init() function, and kept the inheritance of the parent class, and we are ready to add functionality in the init() function.
Python also has a super() function that will make the child class inherit all the methods and properties from its parent: