This Python Inheritance lesson is for a beginner. Read the short notes, run each example, then change one name or number and run it again.
A child class reuses a parent. Put the parent name in parentheses. super() calls the parent method when the child wants the original behaviour plus something more.
Inheritance fits a true kind-of relationship. A batch is not a kind of list, so do not inherit from list just to store names.
Example 1: Start here
If the child __init__ replaces the parent one, call super().__init__ when the parent stores data you still need.
class User: # a template for objects
def __init__(self, name): # runs when you create the object
self.name = name # store this on the object
class Mentor(User): # a template for objects
def label(self): # define the function; it runs when you call it
return "Mentor " + self.name # send this value back to the caller
print(Mentor("Divya").label())
Example 2: A child reuses init
The child class uses the parent __init__ because it does not define its own.
class Course: # a template for objects
def __init__(self, title): # runs when you create the object
self.title = title # store this on the object
class PythonCourse(Course): # a template for objects
pass # a placeholder, so the block is not empty
print(PythonCourse("Python").title)
Example 3: Extend with super
super() runs the parent setup, then the child adds seats.
class Course: # a template for objects
def __init__(self, title): # runs when you create the object
self.title = title # store this on the object
class PythonCourse(Course): # a template for objects
def __init__(self, title, seats): # runs when you create the object
super().__init__(title) # call the function
self.seats = seats # store this on the object
print(PythonCourse("Python", 24).seats)
Example 4: Override a method
The child method replaces the parent method of the same name.
class Course: # a template for objects
def label(self): # define the function; it runs when you call it
return "Course" # send this value back to the caller
class PythonCourse(Course): # a template for objects
def label(self): # define the function; it runs when you call it
return "Python course" # send this value back to the caller
print(PythonCourse().label())
