Skip to content

Classes and Inheritance – Python Object-Oriented

We’ve talked about many of Python Basics in the previous articles, such as List, Dictionaries, and we’ve even practiced with some Python Projects For Beginners. In this article we’re going to cover object-oriented programming in Python, we’ll cover classes objects inheritance and other related concepts. First, we’ll explain some concepts of object-oriented programming. Then we actually have some code that we’ll walkthrough which will make it a lot clearer how these actually work.

Classes and Inheritance : Introduction

There are three main (concepts) cornerstones in Python ObjectOriented Programming. These are: encapsulation, inheritance, and polymorphism.

Encapsulation and composition

  • Encapsulation: is basically combining data and actions into the same block of code called a class. A class is a block of code that instantiate an object. You can think of it as a recipe that helps to bake a pie. You follow the recipe you can make as many pies as you want from that recipe. That’s what a class is, you can make as many objects as you want from that class. Encapsulation includes all the data and actions together in the same block of code.
  • Composition: is the concept that objects can contain other objects in their instance variables. This is a has a relationship. This is really simple. It may sound confusing but car has tires. If you’re modeling a program for a car. You need to say that a car has tires. Then you want a tire object to have a brand name, dimensions, size, and the tread. You have a tire object and a car has a tire and that’s all this is saying. A tire is part of the composition of a car.

What is Inheritance

  • inheritance: The diagram below explains inheritance in a nutshell. It’s basically the idea that you have a hierarchy of classes. You may have a life form. Every life form has a life span. We have this attribute under life form. Then under life form there are plants and there are animals. Let’s say we have an animal life form that has weight. That attribute is under the animal. Basically, every single one of these types of animals have a life span and a weight that can access through its parent class. It’s inheriting all of these attributes plus it adds on some specific attributes of its own class. A reptile may have a number of legs and a boolean for has teeth or not. Then fish could be saltwater or freshwater fish, so is saltwater or length. Birds are basically perching, birds and non-perching birds. Then you also have wingspan. So you have different attributes for birds, plus a bird has a weight and a bird has a lifespan. So it inherits all the parents’ attributes plus the specific attributes of that child class. This is an inheritance.
Python Object Oriented Programming - Inheritance Schema
Python Object Oriented Programming – Inheritance Schema

Classes and Inheritance : abstraction and polymorphism

  • Abstraction: is having an abstract class as a template only, that cannot be instantiated into an object. It serves as a template or a placeholder for you to write a concrete class based on that. It’s really there to just define what methods or functions that you need in that class to implement it.
  • Polymorphism: is really a $10 word for a $1 idea. It’s a lot simpler than it sounds. The idea is really that you’re gonna have a lot of child classes accessing functions of parent classes. You just want these parent class to be able to execute those functions regardless of which child class is calling it. If I call a get weight function in the animal class, it shouldn’t matter whether or not a fish is calling get weight or a reptile calling get weight. It always just returns the weight for that animal. In other words, the get weight function is class agnostic as long as it is an animal or a descendant of the animal class, you can use that get weight function.

Python Object Oriented Programming Advantages

  1. Classes and inheritance reduce the amount of code you have to write and that is because it is modular.
  2. Object-oriented programming helps you modularize your code into classes. Then you can reuse those classes in other programs and other modules, etc
  3. Code reusability: for example, you write a student class. Guess what? not only can you reuse that student class in other programs. You can also share it on Github and other people can use your student class in their program. The concept of code reusability and sharing code gets a lot more mileage out of the code you write. It really does reduce the amount of code and also enables you to use existing code.
  4. Classes and inheritance models the real world. As I just explained in the example with animals, with cars and tires. These are objects and this is how the real world works. Although it is a noun based. Typically in object-oriented programming, you have objects for nouns and then you have functions or methods for verbs or actions. This basically models the real world though
  5. Object-oriented programming is easier to understand, debug, maintain, and extend your code. If I want to add an additional function onto reptile, I can easily do that just using the reptile class. It doesn’t have to affect any of my other code. It’s easier to debug because I’m debugging a much smaller block of code. It’s easier to understand and maintain the code.

Classes and Inheritance : Learn By Coding

These are some advantages of object-oriented programming, now let’s look at some code examples to learn how it works. We’re going to start with a shape class

class Shape:

def init(self, color=None):

self.color = color

We have class shape and a colon, then within that, we have different functions. I started by writing an init function that is a constructor. We always have the first parameterself Then we want to pass in a color, if no color is passed in, it will assign none to color but hopefully, somebody will pass in a color to the constructor when they create a new shape.

Classes and Inheritance : learn with code

class Shape:
def
init(self, color=None):
self.color = color

def get_color(self):
return self.color

def str(self):
return self.get_color() + ' Shape'
shape = Shape ('red')
print ('shape is', shape.get_color())

There’s one function in here: get color. All it does is return the color. So every shape has a color. We also have a two-string method __str __ this is the Python’s string method. In other words, it returns a string representation of a shape. We can define that to be whatever we want. What we’re going to return is just a color then word shape. That’s it, we returned this string that is our string representation of shape.

For a lot of classes you write, you’ll probably want to have a two-string method. it returns some sort of string representation of the class.

To use our shape class, we can just have shape equals shape and then in parenthesis. We’re going to pass in the string red which is our color. We haven’t said what kind of shape this is yet. But we don’t have to at this point, because the shape is just a generic parent class.

Then we can print “shape is” shape get color using our variable here, our instance variable which is called shape, with the lowercase s, we can call the methods of the shape class, and we’re going to get the color of this shape that we instantiated.

This shape of the capital S, basically calls the constructor or the init function within the shape class and passes in the variable read the string red so that’s it it’s pretty simple.

Let’s run that and then you can see it should print out red shape.

Python Object Oriented Programming - Inheritance example
Python Object Oriented Programming – Inheritance example

Final words

That concludes this article on Python object-oriented. I hope this has been helpful. Please help me by sharing this article with your friends and follwers on social media.

Check out my Python For Beginners course to master the basics of Python quickly and efficiently. And follow me on Twitter for your daily update on Python and Data sciece related free content.

45 Comments

  1. I’m commenting to let you be aware of what a remarkable experience my friend’s princess developed checking your webblog. She came to find lots of details, which include what it’s like to possess an awesome giving style to have many people with no trouble learn chosen multifaceted subject areas. You really surpassed her expectations. Thanks for rendering those productive, healthy, edifying and as well as fun thoughts on that topic to Tanya.

    • mustapha mustapha

      Thank you so much, I’m glad to hear from you.

  2. Hello! Someone in my Myspace group shared this site with us so I came to check it out.

    I’m definitely enjoying the information. I’m bookmarking and will be tweeting this to my followers!
    Outstanding blog and amazing style and design.

  3. Currently it looks like WordPress is the best blogging platform out there right now.
    (from what I’ve read) Is that what you are using on your blog?

  4. I think that what you posted made a lot of sense.
    But, what about this? suppose you were to write a awesome headline?
    I am not suggesting your content is not solid., but
    what if you added something to maybe grab people’s attention? I mean Classes
    and Inheritance – Python Object-Oriented – A
    State Of Data is kinda plain. You should look at Yahoo’s
    home page and see how they write post headlines to grab people interested.
    You might try adding a video or a related pic or two to get people interested about everything’ve got to say.
    In my opinion, it might bring your posts a little bit more interesting.

  5. I got what you intend,bookmarked, very decent website.

  6. I like what you guys are up also. Such clever work and reporting!
    Keep up the superb works guys I have incorporated
    you guys to my blogroll. I think it’ll improve the value of my website :).

  7. I was just searching for this info for some time. After
    six hours of continuous Googleing, at last I got it in your site.

    I wonder what is the lack of Google strategy that do not rank this kind
    of informative web sites in top of the list.
    Normally the top sites are full of garbage.

  8. Keep up the wonderful piece of work, I read few content on this site and I think that your blog is
    real interesting and has sets of good info.

  9. I visited many blogs however the audio feature for audio songs existing at this website is genuinely marvelous.

  10. Paragraph writing is also a excitement, if you be familiar with afterward you can write otherwise it is complex to write.

    • mustapha mustapha

      Thanks for your feedback,
      I’m glad to hear from you.
      Thanks.

  11. I’m still learning from you, as I’m trying to achieve my goals.
    I absolutely enjoy reading all that is posted on your site.Keep
    the information coming. I liked it!

    • mustapha mustapha

      Thanks for your feedback,
      I’m glad to hear from you.
      Thanks.

  12. Heya i am for the primary time here. I found this board and I in finding It
    truly helpful & it helped me out much. I’m hoping to present something again and
    aid others like you helped me.

    • mustapha mustapha

      Thanks for your feedback,
      I’m glad to hear from you.
      Thanks.

  13. Hi colleagues, its great article on the topic of tutoringand fully defined, keep it up
    all the time.

  14. Incredible! This blog looks just like my old one!

    It’s on a totally different topic but it has pretty much
    the same layout and design. Excellent choice of colors!

    • mustapha mustapha

      Thanks for your feedback,
      I’m glad to hear from you.
      Thanks.

  15. I could not resist commenting. Perfectly written!

    • mustapha mustapha

      Thanks for your feedback,
      I’m glad to hear from you.
      Thanks.

  16. If you would like to increase your familiarity simply keep visiting this web site and
    be updated with the latest news posted here.

    • mustapha mustapha

      Thanks for your feedback,
      I’m glad to hear from you.
      Thanks.

  17. Hi there, You have done an excellent job. I’ll definitely digg it and personally recommend to my friends.
    I am sure they will be benefited from this website.

    • mustapha mustapha

      Thanks for your feedback,
      I’m glad to hear from you.
      Thanks.

    • mustapha mustapha

      Thanks for your feedback,
      I’m glad to hear from you.
      Thanks.

  18. It’s awesome to pay a quick visit this web page and reading the views of all friends
    about this paragraph, while I am also keen of getting knowledge.

    • mustapha mustapha

      Thanks for your feedback,
      I’m glad to hear from you.
      Thanks.

  19. It?s difficult to find knowledgeable people on this topic, but you seem like you know
    what you?re talking about! Thanks

    • mustapha mustapha

      Thanks for your feedback,
      I’m glad to hear from you.
      Thanks.

  20. Hey there! Do you know if they make any plugins to help with
    Search Engine Optimization? I’m trying to get my blog to rank for some targeted
    keywords but I’m not seeing very good success.

    If you know of any please share. Thanks!

    • mustapha mustapha

      Thanks for your feedback, the only plugin I use for SEO purposes is Yoast SEO.
      I’m glad to hear from you.
      Thanks.

  21. A motivating discussion is definitely worth comment.

    I do think that you ought to write more about this topic, it may not be a taboo matter but typically
    people don’t discuss such topics. To the next!
    Cheers!!

    • mustapha mustapha

      Thanks for your feedback,
      I’m glad to hear from you.
      Thanks.

  22. Hi there, i read your blog occasionally and i own a similar one and i was just curious if you get a lot of
    spam comments? If so how do you prevent it, any plugin or anything you can recommend?

    I get so much lately it’s driving me mad so any help is very much appreciated.

    • mustapha mustapha

      Hi there,
      Thanks for your feedback, yes I get some spam comments but I have no plugin to take care of them, I just walk through them and delete them manually.

  23. Asking questions are really nice thing if you are not understanding anything totally, except this piece of writing provides pleasant understanding yet.

    • mustapha mustapha

      Thanks for your feedback,
      I’m glad to hear from you.
      Thanks.

  24. There’s definately a lot to find out about this subject.
    I like all of the points you made.

Leave a Reply

Your email address will not be published. Required fields are marked *

error

Enjoy this blog? Please spread the word :)