
Before we give Python Class Inheritance Examples, we must explain the concept of Inheritance. You may want to read about the fundamentals of Python Classes before you continue.
Inheritance is a mechanism by which one class inherits the methods and attributes of another class, in the same way a child inherits the behaviors, features and genetics of its parents. It is another concept that belongs to Object Oriented Programming, along with the idea of ‘classes’ and is also supported by the Python Programming language.
The child class or derived class is the class that inherits from the parent class or base class.
Let us define a PARENT CLASS:
class ParentClass:
def __init__(self, surname, human):
self.surname = surname
self.human = human
def printParentFeatures(self):
print(f'''
Surname: {self.surname}
Human: {self.human}''')
x = ParentClass("Johnson", True)
x.printFeatures()
#OUTPUT
#Surname: Johnson
#Human: True
Recall that the special method __init__() sets initial values in the class. The Class Instantiation that happens when we call ParentClass(“Johnson”, True) automatically invokes the __init__() special method which sets the value of the parameter surname and human to Johnson and True respectively. This in turn sets the self.surname and self.human data attributes.
Next, we define our CHILD CLASS:
class ChildClass(ParentClass):
pass
We define our simple CHILD CLASS in the form ChildClass(ParentClass), as seen above. And to prove that we inherited the data attributes and methods of our PARENT CLASS let us declare an object of the CHILD CLASS:
y = ChildClass("Johnson", True)
y.printParentFeatures()
#OUTPUT
#Surname: Johnson
#Human: True
Note from the above that inheritance allowed the child class to inherit the methods and data attributes of the parent class, as promised. We were able to access the printParentFeatures method from the class object y of class ChildClass.
Moving forward we can define a more complete example of our ChildClass:
class ChildClass(ParentClass):
def __init__(self, surname="Johnson", human=True, fname="none", personality="none", bloodtype="none", gender="none"):
super().__init__(surname, human) # super() to access parent
self.fname = fname
self.personality = personality
self.bloodtype = bloodtype
self.gender = gender
def printChildFeatures(self):
print(f'''
Surname: {self.surname.upper()}
First Name: {self.fname.upper()}
Personality: {self.personality.upper()}
BloodType: {self.bloodtype}
Gender: {self.gender.upper()}
Human: {self.human}''')
Notice that we added our own data attributes and methods in the redefined child class.
When we define our __init__() special method in the child class, it overrides the base class __init__() so we must use the super() special method to allow us to access the data attributes in the parent class, in addition to those defined in the child class.
We defined 4 new data attributes: fname, personality, bloodtype and gender. We also defined a new method called printChildFeatures. Let’s define a class object:
z = ChildClass(fname="Clair", personality="sanguine", bloodtype="A", gender="cisgender woman")
z.printChildFeatures()
#OUTPUT
#Surname: JOHNSON
#First Name: CLAIR
#Personality: SANGUINE
#BloodType: A
#Gender: CISGENDER WOMAN
#Human: True
If you need further proof that our child class ChildClass did indeed inherit its attributes and methods from the ParentClass, we can use the built in Python function dir() to see all the members (data attributes and methods) of the ChildClass object z:
print(dir(z))
#OUTPUT
#['class', 'delattr', 'dict', 'dir', 'doc', 'eq', 'format', 'ge', 'getattribute', 'gt', 'hash', 'init', 'init_subclass', 'le', 'lt', 'module', 'ne', 'new', 'reduce', 'reduce_ex', 'repr', 'setattr', 'sizeof', 'str', 'subclasshook', 'weakref', 'bloodtype', 'fname', 'gender', 'human', 'personality', 'printChildFeatures', 'printParentFeatures', 'surname']
You will see that, not only does z inherit the parent members of surname and human, but it inherits quite a few other members which are built into Python.
We can go even further to declare a GrandChildClass and show that it is possible to inherit methods and attributes for more than one base class. This is called MULTIPLE INHERITANCE. See the simple example below:
class GrandChildClass(ChildClass):
pass
Note that we defined our GrandChildClass the same way we defined the ChildClass, in the form GrandChildClass(ChildClass). For this new GrandChildClass, both the ChildClass and the ParentClass act as a base class or parent class.
If we define a class object and then do a dir() on it we can prove that it inherited the attributes and methods of both the ParentClass and ChildClass:
zz = GrandChildClass(fname="Saul", personality="phlegmatic", bloodtype="O", gender="cisgender man")
print(dir(zz))
#OUTPUT
#['class', 'delattr', 'dict', 'dir', 'doc', 'eq', 'format', 'ge', 'getattribute', 'gt', 'hash', 'init', 'init_subclass', 'le', 'lt', 'module', 'ne', 'new', 'reduce', 'reduce_ex', 'repr', 'setattr', 'sizeof', 'str', 'subclasshook', 'weakref', 'bloodtype', 'fname', 'gender', 'human', 'personality', 'printChildFeatures', 'printParentFeatures', 'surname']
Note that we declared an empty class GrandChildClass yet because it is derived from the base class ChildClass it has access to members (data attributes and methods) of both its parents which are the ChildClass and the ParentClass.
Below is the full code:
class ParentClass:
def __init__(self, surname, human):
self.surname = surname
self.human = human
def printParentFeatures(self):
print(f'''
Surname: {self.surname}
Human: {self.human}''')
class ChildClass(ParentClass): #simple inheritance
def __init__(self, surname="Johnson", human=True, fname="none", personality="none", bloodtype="none", gender="none"):
super().__init__(surname, human) # super() to access parent
self.fname = fname
self.personality = personality
self.bloodtype = bloodtype
self.gender = gender
def printChildFeatures(self):
print(f'''
Surname: {self.surname.upper()}
First Name: {self.fname.upper()}
Personality: {self.personality.upper()}
BloodType: {self.bloodtype}
Gender: {self.gender.upper()}
Human: {self.human}''')
class GrandChildClass(ChildClass): #multiple inheritance
pass
x = ParentClass("Johnson", True)
x.printParentFeatures()
y = ChildClass("Johnson", True)
y.printParentFeatures()
z = ChildClass(fname="Clair", personality="sanguine", bloodtype="A", gender="cisgender woman")
z.printChildFeatures()
print(dir(z))
zz = GrandChildClass(fname="Saul", personality="phlegmatic", bloodtype="O", gender="cisgender man")
print(dir(zz))
#OUTPUT
#Surname: Johnson
#Human: True
#
#Surname: Johnson
#Human: True
#
#Surname: JOHNSON
#First Name: CLAIR
#Personality: SANGUINE
#BloodType: A
#Gender: CISGENDER WOMAN
#Human: True
#['class', 'delattr', 'dict', 'dir', 'doc', 'eq', 'format', 'ge', 'getattribute', 'gt', 'hash', 'init', 'init_subclass', 'le', 'lt', 'module', 'ne', 'new', 'reduce', 'reduce_ex', 'repr', 'setattr', 'sizeof', 'str', 'subclasshook', 'weakref', 'bloodtype', 'fname', 'gender', 'human', 'personality', 'printChildFeatures', 'printParentFeatures', 'surname']
#['class', 'delattr', 'dict', 'dir', 'doc', 'eq', 'format', 'ge', 'getattribute', 'gt', 'hash', 'init', 'init_subclass', 'le', 'lt', 'module', 'ne', 'new', 'reduce', 'reduce_ex', 'repr', 'setattr', 'sizeof', 'str', 'subclasshook', 'weakref', 'bloodtype', 'fname', 'gender', 'human', 'personality', 'printChildFeatures', 'printParentFeatures', 'surname']
We hope that the above Python Class Inheritance Examples tutorial helped. Cheers! 👌👌👌