Practice Exams:

Python Institute PCAP – Modules, Packages and Object Oriented Programming in Python Part 3

  1. Abstract Classes and Methods

Now what’s? An abstract class. Well, an abstract class is a kind of class that is not supposed to be used for creating objects from okay, you cannot create an instance of an abstract class meaning you can’t create an object out of an abstract class you’re not supposed to. Now, python does allow a little bit of this, and then you have to kind of design your program in such a way that it throws an error when someone tries to do anything with an object that was created from an abstract class.

And I’ll show you how to do that. So the idea behind an abstract class is it’s only meant to be inherited from an abstract class is a parent class that should only be inherited from you should not be actually creating instances and doing things with it. So it’ll make more sense when I go over an example. So I’m going to change the example here just to give you a bit more variety. We were dealing with vehicles up to this point. And so that’s in the vehicles excuse me. In the Machines folder let’s create another folder here called Animals. And for those of you that are familiar with my object oriented tutorials on Java, on YouTube, as well as in my other courses, I discuss animals quite a bit.

So we’re going to sort of replicate that idea in this in python. So animals. Let’s create a class or file rather. We’re going to create a Python file and we’ll say animal stuff. That’s It. So we’ll create a class called excuse me, a file called Animal Stuff. And in this file, we’ll have various classes that have to do with animals. Now again, design note you shouldn’t be creating vehicle classes or things to do with machines in this animal stuff class.

Right? That’s just a bad design. So that’s why keep in mind we separated these two files. This has the vehicle classes. This animal stuff. File has the animal classes. So let’s create an animal class. A parent animal class. So we’ll define it up here and we’ll say animal. And let’s just keep it simple and say that the animal will still need the init function to be able to create attributes for a given animal. Let’s say that the animal has a name and we’ll leave it to that. And so we’ll do. Self. Name is equal to name. All right.

And to keep it easier to understand, we’ll name this animal let me spell that correctly. Animal underscore name. And then the name that’s passed in as an argument to the constructor is going to be assigned to animal name. Now, you might be thinking, well, you’re not supposed to create an instance of an animal. If we’re trying to create an abstract class, we’re supposed to actually inherit from this class. Well, this construction of an animal. We’re going to inherit this functionality in our child class. So for now, that’s all I want to leave in animal.

And we’ll get back to the animal class shortly. So we’ll define another class called, let’s say monkey. And how do you inherit from a base class? You put the parentheses and you specify the parent like that. This is the base class or the parent class, and this is a child class or the subclass. And so as part of the body of this, we’ll have various methods. And for now, I’m just going to put a pass here and we’ll come back to this class. Let’s come back into the animal class and let’s say that we have a method in this class called Eat.

So we’ll call it eat. And instead of doing something in this method like printing or performing some kind of task, I’m actually going to raise an error. Okay, raise an error. And we’re going to talk more about exception handling and errors later in the course. But for now, I’m just going to introduce to you this syntax and just take it for what it is. We’ll discuss it in greater detail later. But I can raise a particular kind of error and I’m going to call it Not Implemented Error. Okay? And so in here I can say child class should be implementing this, this abstract method.

Or I could just say implementing this just to keep things simple. So this is the crux of what an abstract class is in Python. So now if somebody now we’re outside of the monkey class, we’re down here to bigger and better code. If someone tries to create an instance of animal and say my dog is equal to animal, they of course have to pass a name.

So we’ll say Jojo. Let’s say the dog is named Jojo. I could say my dog Eat. Now what happens? Let’s try to run this. Hope that didn’t work. And the reason is because I’m still running the application PY file. If you look on the top right, I’m glad this happened so that you don’t run into this. Notice if you drop down this application little box here, you can choose which one. Now you may not have animal stuff here yet, so if you right click and click on Run animal Stuff. Let’s run it. And now we’ll see the error. Okay, so if you run this by hitting the play button and you don’t see the error, that’s because we are trying to run this file, not the application PY file that we’ve been running so far in the course.

And you have to change the file that gets run. So you have to right click this file and run animal Stuff. So now what is the error that it’s showing? It’s showing raise, not implemented error. Child class should be implementing this, right? So it’s giving us the message that you can’t invoke the Eat method on the animal class directly. Okay, so what do we do? Well, we can of course follow the recommendation here. Child class should be implementing this. So let’s actually create the eat method in the child class, which is monkey. So we could do deaf eat. And this is just going to say print monkey eating bananas. Okay. So now I’m not going to use the animal class to create an instance. I’m going to create the class that we have available, which is monkey. So I’m going to use that monkey. And let’s just say that our monkey, his name is Jojo, and I’ll say my monkey.

And we could say my monkey eat. And let’s run this. And now it should say monkey eating bananas. Make sure you’re running this file when you right click. Once you change it up here, then the hitting the play button would be fine. When we move back to the application PY file, you’re going to have to change it back up here to run the application PY file.

All right, hopefully that makes sense. So hopefully you get the idea. Now if I have another animal here, let’s just say bird, and that also inherits from the animal based class. And so the bird might have well, it’s definitely going to have an eat method. And we can say bird eating seeds or something. I guess that’s what they eat. And then we can have another method in here called fly because birds can fly. And so bird soaring high. Okay? And so then we can create a bird. So we say my bird is equal to bird, and we pass in the bird name, which is let’s just say our bird is named Tim, and we can make Tim fly.

That’s a terrible name for a bird, but we’ll leave it to that, okay? And so hopefully you get the idea. So this particular method we cannot run on an animal directly. We have to inherit from the animal class and create a subclass like monkey or bird or any other animal that inherits from the animal class. We can invoke the eat method on that. All right, now monkeys don’t fly, so you wouldn’t have a fly method in monkeys, but they can run or climb, which birds probably cannot. So those methods would be specific to a monkey. So hopefully you get the idea. We get the base functionality of an animal by using this particular method to instantiate a monkey or a bird, right? So we’re using this constructor in the animal class so that we don’t have to define the constructor again in monkey or bird and then the eat method that’s in animal. Obviously all animals eat. So this is sort of a base functionality and we don’t want it to implement it in the animal class.

We’d like the monkey to be able to eat bananas. We’d like birds to be able to eat seeds, and we’d like, for example, cows to be able to eat grass and so on. Hopefully you get the idea. All right, so we talked a lot about object orientation in the last couple of lectures. And these are very crucial lectures, and so make sure you revisit them if you forget some of this stuff and practice. So you might be wondering, where are the animals and what does an animal have to do in our software? Or why are we creating all these cars and trucks? Is this a software or are we talking about a Tesla factory or are we talking about a farm?

So to be able to present these ideas to you, I use these concepts such as animal and a vehicle to keep things simple. But in the next lecture, we’re going to actually get a little bit practical and you’ll see these ideas that I shared with you in a practical application, right, where you actually have to do things. Because, again, code is just instructions to the computer, and object oriented programming is a way of writing your code so that it’s reusable.

We’re reusing the animal class here multiple times to be able to create a bird or a monkey because we know that we need a name, and that code has already been defined up here, so we don’t need to rewrite that code in the bird or the monkey. So you’re going to see this kind of action in an actual program that does some kind of operation in a typical software, and this will get much more practical. When we talk about reading and writing files, you may have two different types of subclasses of a file reader. For example, you may have a parent class called file reader, and you may have two subclasses. One class might be responsible for reading spreadsheets.

The other file might be responsible for reading PDFs. Another class might be responsible for reading Word docs, right? They may all have some shared functionality with the parent file reader class. But obviously the way to read PDF files is very different, different than the way to read Excel spreadsheets or Word documents. So in the next lecture, we’re going to expand upon this idea and actually work with something that has to do with a computer performing some kind of operations rather than these abstract monkey and animal.

  1. Practical Application of OOP

These animals and machines like vehicles and dogs and cats. And obviously we’re not dealing with any, nor is this a zoo, nor is it a Tesla car factory, right? We were writing a computer program, but to discuss the concepts of object oriented programming and what a class is and the parent class and the child class and how functionality is inherited and so on those concepts, to explain those concepts, I use these imaginative examples, right? But now let’s go over an actual program, which is still going to be a very simple program, but it’s going to have more to do with writing code that actually does stuff, because what is code? Code is instructions to the computer on what to do. And these are operations that we need to perform. And so object oriented programming is a way of organizing our code so that it’s reusable. All right?

And so we’re going to expand on that idea now with a practical example. And so what I’m going to do now is I’m going to create a new folder, and let’s say we’ll title this folder Utils, which stands for utilities. And so right here I’m going to create a new file in this Python file, and we’ll call it utilitystuff PY. And this is going to essentially have code that we can reuse that might help us do things. And the example that I’m going to use for this lecture is the ability to shorten lists or dictionaries to slice them and get only the first three elements in a list in a sequence of characters in a dictionary. So we’re now going more to words and actual code that is going to perform instructions rather than these imaginary ideas of animals and machines.

And the reason why I named this file Utility stuff is because it can be used to have various classes in it that can help us perform various operations in any given software. And so we’re going to create three classes, and one of them is going to be a parent class. And we’ll call this class shortener because essentially this is going to help us shorten things to three elements, whether it’s a list, a dictionary, a sequence of characters. And this is going to be the parent class and I called a shortener. And so we need a constructor here.

So the constructor is this, okay? And it accepts self, obviously, as the first argument, which refers to the object when we instantiate an instance. And then the second argument is going to be the items. And these items could be, like I said, a sequence of characters like a string, a list or dictionary, okay? And so what I’m going to do is I’m going to define a variable called original items. And this will get assigned the items that a user passes into it. And so the way I envision how a user would use this is if they wanted to create a shortener, they would just do my shortener is equal to and pass in either a list of things like numbers or string, such as a sentence or a dictionary, okay? So this constructor is supposed to construct an object that will be able to shorten things and we’ll write the instructions of how to shorten a dictionary or list and that sort of thing.

So we’ve got the constructor method. One more method that I wanted to find in this base class or this parent class because we’ll soon have child classes. And that’s going to be just to print original items because we want to make sure we capture the original items. And this is just going to print self original, okay? And that’s it for our shortener. Now we need specific versions of this shortener. One version could be to deal with strings and lists, because the way to slice strings, as you remember from the slicing chapter when we talk about lists and how we can use those bracket notation to slice a list. And shorten it. One class will be concerned with slicing lists and characters, but there’s going to be a totally different way of slicing dictionaries. Right? And we’re going to actually write the code for that. So two child classes that will inherit from the shortener class.

So we’re done with the shortener. That’s all we need. Now we need a class for list and car shortener, okay? And this class is going to be responsible for being able to you can read it. It shortens either characters or lists and it inherits from the shortener like this. And so we’ll have just one method in here, and that method is going to print shortened items, okay? And it’s going to print self original items and we’re going to slice them from zero to three to get the first three characters or elements within a list, okay? So this is one class that inherits from our base class shortener. And so let’s actually utilize this class. So I’ll call it my shortener is equal to list and car shortener. And I’ll pass in, let’s say, a sentence. This is a sentence. Now I can invoke my shortener print shortened items, right? And so it’ll print the shortened version of this sentence.

Now right now, I’m in Utilitystuff PY. So make sure if you want to run this file. And essentially this is just defining classes up here. But the actual code that’s going to run when we’re calling this method is down here. So we’re going to run this file. We get right click here and go to run utility stuff. So let’s run this and notice there you go. It printed only the first three characters. This class would work the same way if we had a string excuse me, a list. So let’s just have 123456. And so let’s run this and we get one, two, three. Great. So this seems to be working properly. Now with a dictionary, this will not work because we can’t slice a dictionary like this. So we’re going to create a different class with a different version of the print shortened items method, okay?

And by the way, this class, since it’s inheriting from the shortener class, which is the base class, we have access to print original items. So instead of printing shortened, I can also just get the original items, make sure we change this to original. And there we go. We have access to this. And if we run this, we get the original items. So this functionality we’re actually inheriting from the base class. All right, so hopefully you can see that we are reusing some of the code from the shortener based class because this list car shortener subclass inherits that functionality.

Okay? So we’ve got our second class. Now let’s create a third class, which is going to also inherit from the parent, which is called shortener. So we’ll call this class dictionary shortener, because this will be able to shorten dictionaries, and it of course, inherits from the shortener parent class. And so in here I’ll have a similar method with def printed shortened items. But the body of this method is going to be totally different.

So here we can have, for example, a dictionary that will contain the original items, self original. And what is the self, by the way? This is the same self that was passed in to construct an object of either a list or a dictionary, right? So that same original items now is going to be a dictionary now and reassign it to this dictionary variable. So let me comment here. I’ll just add a comment I had off screen. I’m going to paste it here. So essentially what original items will contain is going to be something like this. It’s going to contain this dictionary and we’re assigning it to a dictionary variable. Now, how do we go about slicing this thing? So first what I’m going to do is I’m going to create a counter. And you can do this as an assignment.

You know enough about python. Now, if you’ve been practicing to be able to write this code yourself, so why don’t you pause the video and try this out on your own? This is a good practice for you to have. Complete this assignment, and then you can resume to watch my solution. Welcome back. Hopefully you attempted that. So I’m going to create a counter variable. And there’s multiple ways of doing this, but we’ll create a result dictionary which will contain the result of the shortened dictionary. And so now that we have that, I’m going to loop through the key value pairs.

So KV in dictionary items, remember this. And so now that we can loop through the dictionary items, we can check whether if the counter is less than three, right? Then we’d like to append or update the result dictionary. And there’s this update method, and this basically just adds to the dictionary. So think of this as an append like Listepend update is very similar to a pen, but it’s used for dictionaries. So we’re going to add the particular k and V value, all right, that gets added to the result dictionary. And so we of course have to increment counter so that we end this loop eventually. Because once counter reaches three, this loop will end. It’ll start from zero and it’ll end at when counter is equal to three. And by then we would have populated this result dictionary with three items. And so that’s it. Now outside of this for loop, now we’re just going to print the result dictionary, all right?

And this of course is still in the body of this print shortened items method. And so now let’s test this out. I’m going to create a new object and I’ll call it my shortener. And this will be a dictionary shortener. And the data that we pass to it is going to be a dictionary. So let’s just copy it from here, this example, and you can pass in whatever dictionary you choose. And so now not only do I have my shortener the ability to check the original items, we can print the original items because again, this is inheriting from the base class shortener. And that base class has print original items. Not only do we have the ability to do that, but we also have the ability to shorten it. So let’s first run this, make sure you’re selecting the Util stuff file. Right click run this file and there we go.

These are the original items that we passed to this method, or to this object rather. And so now let’s shorten it so we could do print shorten items. And now we should only see Mike, Tom and Rebecca in the results. So let’s run this. And there we go. Mike, Tom and Rebecca. So the functionality is working. So now we have this Utility stuff file that contains some handy code that we can use sometime in the future whenever we need to shorten a dictionary or list to three items.

So I could just close this file and here’s the Utils folder and our application PY. Right, let’s change this back to application PY. And just let me quickly remind you how you can import that given code that we wrote in the Utils folder and the utility stuff. So if we were to, for example, let’s just do from Utils and you can see the folder name right there, utility Stuff, because that folder can have multiple files, is the file that we have import the given class that we want to import.

So we can import the list and character shortener as well as the dictionary shortener. And so I think I still have that code in the bottom of the utility stuff right here. So I could just literally copy this code and run it in application PY. And so let’s make sure this is highlighted as application now let’s run this application PY file. And there we go. Notice it’s working. Now, notice that we have two outputs here. Why is that? Why do we have two outputs here? Can you take a guess as to why this is happening? Why don’t you take a moment and think about it, and then you can resume to watch my solution about explaining to you why this is happening. Okay, welcome back.

Hopefully you thought about it and were able to figure out the reason why these two are happening is because, first of all, we’re importing Utility Stuff file, and whenever we perform some kind of operation here, we’re invoking this print shortened items. We’re using some of the code that’s in that file. What else is in that file? In that file we have this print shortened list. Okay, I’ll prove it to you. If I change this from Mike to John and all caps so we can easily identify Tom capital. Becca, I think Rebecca ze only has one C. I’m not sure. And then Mike, this is all capital, so we can differentiate where this is coming from, and let’s save it. And now let’s run the application, that PWA file. Again, notice this gets run first because that’s coming from the utility stuff file, right? Whereas this is coming from this file. As you can see, these are shortened excuse me, lowercase.

So hopefully you understand why that’s happening. So if you put away things in a file and it has classes and a program structure like this, don’t tap stuff like this in it, okay? Keep that in mind. And so now I got rid of that. And so when I run this, I’m only going to see one entry here. Okay? So there you go. A real life sort of example of how you can write instructions for a computer program and still apply the concepts that we talk about with object orientation and inheriting functionality from a base class. So hopefully this satisfied your appetite of a real program. Although it’s still very basic, but it’s still a real program compared to creating.