No Result
View All Result
DevRescue
  • Home
  • Python
  • Lists
  • Movies
  • Finance
  • Opinion
  • About
  • Contact Us
  • Home
  • Python
  • Lists
  • Movies
  • Finance
  • Opinion
  • About
  • Contact Us
DevRescue
Home Blog Python

Python Class Inheritance Examples

by Khaleel O.
June 18, 2021
in Python
Reading Time: 8 mins read
A A
Python Class Inheritance Examples
Python Class Inheritance Examples

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! 👌👌👌

Tags: Multiple Class Inheritance in PythonPython Class Inheritance Examples
Previous Post

Python AES 256 Encryption Example

Next Post

Break List Into Chunks with Python

Khaleel O.

Khaleel O.

I love to share, educate and help developers. I have 14+ years experience in IT. Currently transitioning from Systems Administration to DevOps. Avid reader, intellectual and dreamer. Enter Freely, Go safely, And leave something of the happiness you bring.

Related Posts

Python

Python Fibonacci Recursive Solution

by Khaleel O.
January 16, 2024
0
0

Let's do a Python Fibonacci Recursive Solution. Let's go! 🔥🔥🔥 The Fibonacci sequence is a series of numbers in which...

Read moreDetails
Python

Python Slice String List Tuple

by Khaleel O.
January 16, 2024
0
0

Let's do a Python Slice string list tuple how-to tutorial. Let's go! 🔥🔥🔥 In Python, a slice is a feature...

Read moreDetails
Python

Python Blowfish Encryption Example

by Khaleel O.
January 14, 2024
0
0

Let's do a Python Blowfish Encryption example. Let's go! 🔥 🔥 Blowfish is a symmetric-key block cipher algorithm designed for...

Read moreDetails
Python

Python Deque Methods

by Khaleel O.
January 14, 2024
0
0

In this post we'll list Python Deque Methods. Ready? Let's go! 🔥🔥🔥 A deque (double-ended queue) in Python is a...

Read moreDetails

DevRescue © 2021 All Rights Reserved. Privacy Policy. Cookie Policy

Manage your privacy

To provide the best experiences, we and our partners use technologies like cookies to store and/or access device information. Consenting to these technologies will allow us and our partners to process personal data such as browsing behavior or unique IDs on this site and show (non-) personalized ads. Not consenting or withdrawing consent, may adversely affect certain features and functions.

Click below to consent to the above or make granular choices. Your choices will be applied to this site only. You can change your settings at any time, including withdrawing your consent, by using the toggles on the Cookie Policy, or by clicking on the manage consent button at the bottom of the screen.

Functional Always active
The technical storage or access is strictly necessary for the legitimate purpose of enabling the use of a specific service explicitly requested by the subscriber or user, or for the sole purpose of carrying out the transmission of a communication over an electronic communications network.
Preferences
The technical storage or access is necessary for the legitimate purpose of storing preferences that are not requested by the subscriber or user.
Statistics
The technical storage or access that is used exclusively for statistical purposes. The technical storage or access that is used exclusively for anonymous statistical purposes. Without a subpoena, voluntary compliance on the part of your Internet Service Provider, or additional records from a third party, information stored or retrieved for this purpose alone cannot usually be used to identify you.
Marketing
The technical storage or access is required to create user profiles to send advertising, or to track the user on a website or across several websites for similar marketing purposes.
Statistics

Marketing

Features
Always active

Always active
  • Manage options
  • Manage services
  • Manage {vendor_count} vendors
  • Read more about these purposes
Manage options
  • {title}
  • {title}
  • {title}
Manage your privacy
To provide the best experiences, DevRescue.com will use technologies like cookies to store and/or access device information. Consenting to these technologies will allow us to process data such as browsing behavior or unique IDs on this site. Not consenting or withdrawing consent, may adversely affect certain features and functions.
Functional Always active
The technical storage or access is strictly necessary for the legitimate purpose of enabling the use of a specific service explicitly requested by the subscriber or user, or for the sole purpose of carrying out the transmission of a communication over an electronic communications network.
Preferences
The technical storage or access is necessary for the legitimate purpose of storing preferences that are not requested by the subscriber or user.
Statistics
The technical storage or access that is used exclusively for statistical purposes. The technical storage or access that is used exclusively for anonymous statistical purposes. Without a subpoena, voluntary compliance on the part of your Internet Service Provider, or additional records from a third party, information stored or retrieved for this purpose alone cannot usually be used to identify you.
Marketing
The technical storage or access is required to create user profiles to send advertising, or to track the user on a website or across several websites for similar marketing purposes.
Statistics

Marketing

Features
Always active

Always active
  • Manage options
  • Manage services
  • Manage {vendor_count} vendors
  • Read more about these purposes
Manage options
  • {title}
  • {title}
  • {title}
No Result
View All Result
  • Home
  • Python
  • Lists
  • Movies
  • Finance
  • Opinion
  • About
  • Contact Us

DevRescue © 2022 All Rights Reserved Privacy Policy