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 Object
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
thatan 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. instantiate
- Composition: is the concept that objects can contain other objects in their instance variables. This is
a hasa relationship. This is really simple. It may sound confusing but carhas 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
formthere 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 havea 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.
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
- Classes and inheritance reduce the amount of code you have to write and that is because it is modular.
- Object-oriented programming helps you modularize your code into classes. Then you can reuse those classes in other programs and other modules, etc
- 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.
- 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
- 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
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 parameter
self 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
self.color = color
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
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.
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
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
Hey there just wanted to give you a quick heads up.
The text in your article seem to be running off
the screen in Firefox. I’m not sure if this is a formatting issue or
something to do with internet browser compatibility
but I thought I’d post to let you know. The layout look great though!
Hope you get the issue solved soon. Cheers
For newest news you have to go to see internet and on the web I found
this web page as a best site for hottest updates.
Oh my goodness! Incredible article dude! Thank you so much, However I am having difficulties with your RSS. I don’t understand why I can’t subscribe to it. Is there anyone else getting similar RSS issues? Anybody who knows the answer will you kindly respond? Thanx!!
Tremendous issues here. I’m very glad to see your article.
Thanks so much and I am taking a look forward to touch
you. Will you kindly drop me a mail?
Hey there would you mind sharing which blog platform you’re
using? I’m planning to start my own blog soon but I’m having a tough
time selecting between BlogEngine/Wordpress/B2evolution and Drupal.
The reason I ask is because your design and style
seems different then most blogs and I’m looking for something completely unique.
P.S Apologies for being off-topic but I had to ask!
Your style is so unique compared to other people I’ve read stuff from. I appreciate you for posting when you’ve got the opportunity, Guess I will just bookmark this site.
Hello there, I discovered your blog by the use of Google even as looking
for a similar topic, your website came up, it looks good.
I have bookmarked it in my google bookmarks.
Hi there, simply turned into alert to your blog thru Google, and
found that it’s really informative. I’m gonna be careful for brussels.
I’ll be grateful in the event you proceed this in future.
Many other people might be benefited from your writing.
Hi, I check your blog on a regular basis. Your humoristic style is witty,
keep doing what you’re doing!
I constantly emailedthis weblog post page to all my a
Having read this I thought it was really informative.
I appreciate you spending some time and effort to put this content together.
I once again find myself personally spending a significant amount of time both reading and posting comments.
But so what, it was still worthwhile!
Hello there! This is my first comment here so I just wanted
to give a quick shout out and tell you I genuinely enjoy reading
your articles. Can you recommend any other blogs/websites/forums
that deal with the same subjects? Thanks for your time!