Tutorial #10 Python: Inheritance and Multiple Inheritance in object-oriented programming

in #utopian-io8 years ago (edited)

What Will I Learn?

  • Differentiate between a Super class and a sub class
  • Add attributes to an object by class inheritance
  • Access methods that belong to different classes
  • Use multiple inheritance between classes with different attributes

Requirements

  • Basic knowledge of programming
  • Have Python 3.6.4 installed
  • Have Sublime Text or Ninja-IDE installed (optional)
  • Read the previously published tutorials

Difficulty

  • Intermediate

Tutorial Contents

portadas.jpg
Source

Welcome to this tenth Python tutorial where we will do the second part of object-oriented programming, but this time we will explain what is inheritance and multiple inheritance, remember that it will be understood that you read the previous tutorial, first we will proceed to explain the inheritance with a very practical exercise followed by multiple inheritance, let's begin.

Inheritance

Before including your term within the programming, you can define the inheritance as attributes that are passed from generation to generation either between animals or things, for example, you can inherit a mole, attitudes, skin color among many things more than your father, mother, grandfather, etc., in object-oriented programming we can make use of this term, since objects can inherit functions, attributes, methods or properties of another object, this in code would be called "class inheritance" where there is a main class called "super class" and a derived class known as "sub class".

To see how this would be within the object-oriented programming we will use a very famous series called "Game of Thronos" we will use the Stark family, we will create a super class, sub class with their respective attributes, let's see the following image:

Stark.jpg

Through this family we will do the above mentioned, taking into account the inheritance of the children of the Stark parents which will be the objects in our code, always use the previous reference image so that you can clearly understand the concept of the code that will be given then.

First we will create our Super class, which will be represented by the pillars of the Stark family which are Eddard and Catelyn, then we will make the sub class where will be inherited attributes of the super class, this is where the objects that in this case are the children of the Stark pillars will have different names, but they will share the same surname, let's see the following code:

class FamilyStark:
    """Super class family Stark"""
    print ("Children of Eddard and Catelyn Stark")
    def __init__(self, name_stark):
        self.name_stark = name_stark
class InheritorStark(FamilyStark):
    """Sub class that inherits attributes
    of the FamilyStark class"""
    def name(self, name, name_stark):
        print("My name is", name, "heir of the house", name_stark)

1.jpg

In the Super class we only define the surname "Stark" which will be the inherited attribute for all the objects in this case, in the sub class "InheritorStark" we call the super class, here we only take into account the name of each object and we will take the inheritance that would be the surname "Stark", now we will proceed to instantiate the objects and finally access the attributes and methods adding the following lines of code:

#We instantiate the objects of the sub class InheritorStark
robb = InheritorStark("Stark")
sansa = InheritorStark("Stark")
arya = InheritorStark("Stark")
bran = InheritorStark("Stark")
rickon = InheritorStark("Stark")
#We access the methods and attributes
print(robb.name("Robb", robb.name_stark))
print(sansa.name("Sansa", sansa.name_stark))
print(arya.name("Arya", arya.name_stark))
print(bran.name("Bran", bran.name_stark))
print(rickon.name("rickon", rickon.name_stark))

2.jpg

As we can see in the case of the object "robb" we assign the surname "Stark" to the moment we use the sub class "InheritorStark ()", the value that we place inside the parentheses will be the inheritance that we define in the Super class in line 5 of the previous image, finally let's get to the methods and attributes taking the parameter ".name" we give the name to the object, only the inheritance is missing, we use "robb.name_stark", that way we will obtain the following result:

3.jpg

If they are all set to inherit the surname "Stark" with totally different names, the "none" value that shows on the screen is due to the fact that we are not returning any specific value in the sub-class method, at the beginning it can be a bit confusing , what must be taken into account is the attribute that we want to inherit all the objects, this helps us to classify the objects, if we take into account the other families each one would have its own Super class and sub class.

Multiple Inheritance

Python is a language that allows a sub class to inherit attributes of different classes, this is done when we know that an object has different common attributes of classes already created, for that we will take a simple example of a family, where there is a grandfather, mother and a son, where each one would be a class, taking into account that the grandfather would be the super class and the other sub classes, let's see the following code:

class Grandfather: #super class
    def __init__(self, height):
        self.height = height
class Father:#Sub Class
    def hair(self):
        return "Black"
#class that inherits attributes of grandfather and father
class son(Grandfather, Father ): 
    pass #is used when no action is necessary

4.jpg

As you can see we created the three previously indicated classes, in this case we are going to instantiate the object with the name of "Pedro" which inherited from his grandfather the height, but from his father the hair of color "Black", we simply added these lines of codes to instantiate and access the methods:

pedro = son("tall")
print("Thanks to my grandfather I am", pedro.height)
print("For my dad my hair is", pedro.hair())
ext = input("Press enter to exit")

5.jpg

In this way the object "pedro" is taking attributes of two classes this we can do with infinities of classes, but for practical reasons we only take two, but if you like you can add a class called "mother" and make an attribute for our object " pedro ", the final result of this small exercise would be the following:

6.jpg

So we conclude with the essential part of object-oriented programming in Python, it is up to you to practice with different exercises that you can perform yourself taking as examples the aforementioned, likewise in the next tutorials we will use everything we have learned to carry out programs with all the terms and codes that we have seen. Remember that if you have any questions you can use the comment box. See you at the next one!

Curriculum



Posted on Utopian.io - Rewarding Open Source Contributors

Sort:  

Thank you for the contribution. It has been approved.

You can contact us on Discord.
[utopian-moderator]

Nice Python tutorials! I've been posting a few myself that have a more demented twist to them :) I love to see the Python community on here!

I only heard of this python program .,but never been part of it... Is it too late to learn at this my age. ??/

It's never too late to learn @kokomma001, python is a very friendly language, if you like to learn it you can follow it from my first tutorial.

¡Hombre! ¡Usted no descansa! Desde hace tiempo @feuerbolt y yo queríamos conocer un poco más sobre python, creo que en algún momento te fastidiaré con dudas!

A bueno, aquí estamos, cualquier duda estaré a la orden, igual hechale un ojo a los tutoriales pasados, están nutridos de bastante información =)

Great stuff - extremely useful and very well explained :)

I first learned object orientation using Smalltalk - anyone remember that?

Problem is, they used weird analogies like hovering frogs trying to cross a highway ... if the frog can hover, why can't it just fly over the cars ;)

GoT is a much better way to describe it :D

Really the frog always seemed strange to me, an analogy that I consider totally strange

Hey @gabox I am @utopian-io. I have just upvoted you!

Achievements

  • Seems like you contribute quite often. AMAZING!

Suggestions

  • Contribute more often to get higher and higher rewards. I wish to see you often!
  • Work on your followers to increase the votes/rewards. I follow what humans do and my vote is mainly based on that. Good luck!

Get Noticed!

  • Did you know project owners can manually vote with their own voting power or by voting power delegated to their projects? Ask the project owner to review your contributions!

Community-Driven Witness!

I am the first and only Steem Community-Driven Witness. Participate on Discord. Lets GROW TOGETHER!

mooncryption-utopian-witness-gif

Up-vote this comment to grow my power and help Open Source contributions like this one. Want to chat? Join me on Discord https://discord.gg/Pc8HG9x

Coin Marketplace

STEEM 0.04
TRX 0.32
JST 0.075
BTC 64482.23
ETH 1686.47
USDT 1.00
SBD 0.42