Practice Exams:

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

  1. Double Under (Dunder) Methods

And these methods are used to enhance the features of our class. So we’ve been creating basic classes so far. And when we create an instance of that class, when we print it out, it doesn’t even give us a useful representation. So, for example, if I create a class called employee and I define the init method, make sure you use the def keyword before that. And let’s say to instantiate an employee, we need to give a name and age. And so we could do self name is equal to the name that’s passed in, and self age is equal to the age that’s passed in when a user tries to create an instance of the employee. And so now if I try to create an instance of employee, I could do tom is equal to employee and pass in. Tom, for example, is the name Lannister, and the age is 47. Okay, now let me just get rid of all this white space here. Now, when I run this well, before I run it, let me try to print tom. Let’s run it. Notice it gives us a string representation of what this object is supposed to look like, right? This is not helpful to us at all. It doesn’t give us any data about the object tom.

And so there’s really no way of us knowing what this object is. It gives us the place in memory, but that’s not really useful to us. So how do we create a string representation of an employee? Well, we can use a special method, the Dender method known as string underscore, underscore, string dunder method, as you can see, the double underscores. And so now this method allows us the ability to define an object of this class in a string format. So this will return, for example, the name. So we’ll do return name. We’ll make sure we add the self name and then plus, and I can say age is and then I append the actual age. Now make sure we put STR around the age because that’s a number, right? And that’s, of course, going to be self age. You’ve seen the STR method.

This is used to convert, for example, a number or a float or any other decimal type number or anything that is not a string into a string representation. So now, since this is a string, it’s going to concatenate fine. It’s going to be able to combine these two things together and return this sentence properly. So now let’s try to print tom. Let’s run it again. And boom. There you go. Tom Lannister age is 47. What’s happening internally is that the print function is actually looking for the string representation of this object. Now, the list class that is part of the Python libraries already has this configured. So if I create a my list and say that it just has random numbers in it, if I try to print my list, it’s going to actually give me a string representation of this list. It’s not going to give me a memory location in the computer as it was doing before for our object that we created. Because in the list class, an street defined in a list class. Now, another commonly defined method that is a double underscore method is Len. Len. And that’s used for representing collection of items.

So we have a list here. So if I do an Len on my list and let’s print out the value of this and let’s run it, notice it tells us four. So Len is able to calculate the number of items in the list. Now, if I try to do run Len on, for example, Tom, let’s do that. Let’s hit run. Notice it gives us an error object of type. Employee has no len. All right? So if we were to define this double underscore method in this class, len, double underscore, and then it returns us, for example, some number, let’s just say 45. Let’s just say it returns the age. Now, of course, this method doesn’t make sense for an employee. I mean, what is the length of the employee? But it’s used for a collection of items. But I just want to show you that this could be used on any object. And now if we invoke Len on Tom, it’s going to give us this given number, whatever that number is, and that’s 47 in our case.

So let’s run this. And there we go. It’s showing us 47. Now, you can Google the rest of the methods and there are a couple of different ones that you can define. Here’s a website here with a little tutorial on Dunder methods. And notice here are some of these. Sometimes they’re called magic methods. That just sounds more complex than it is. As you can see, these are very simple methods. Double under methods, double underscore methods. So Init is one of them, ad is another. We’ve already looked at Len, we’ve looked at STR, this is another one. So you can go through this tutorial and look at some of the things you can do with these kinds of methods. Here’s another one underscore underscore name. And this is actually a pretty useful one to have, which we’ll talk about later. But this is a nice little tutorial on geek.

  1. Python Script Files

A script is basically a file that contains instructions to the computer on what to do, and it’s meant to be self contained. So you have a script, you have this file that has some code, and it could be Python code, it could be Ruby code or some other like Pearl is another programming language bash. There are various languages and you can just have script files where you just have code that does some operations within the operating system, such as move files around, download data from the Internet, whatever you code in that script. So the idea behind a script is a self contained file. You can even email it to somebody, you can upload it to some server and someone can download it and run it on their machine. And it’s just meant to be an executable file rather than having a project like now. This is a very primitive project that we’ve created so far, and don’t worry, we’re going to be expanding upon this. And I should have changed the name from Hello World, because it’s no longer really a hello world example, but we’ve just been writing code in the same project.

But let’s actually create a script file so that you can see what exactly that is. But before I do that, I want to show you that in your command prompt, or terminal, whatever operating system you’re using, if you’re using Windows, you can open the command prompt, which is that black screen with fancy looking cursor to type commands to the computer. Or if you’re in Mac, there’s something called a terminal which looks like this, right? Another name for this is the command prompt in Windows. So let me just expand this a bit so that we can see all the commands that I’m about to type. So this terminal is a way to access things in the computer. There’s various commands, and you can look these up yourself. I’m not going to go over Linux commands here, but LS is, for example, a command to list the contents of a given directory. So this is our directory, and in this directory, I can create a file, a Python file, and then run that file. I can email that file to someone else and they can run it on their machine. They may have to make a few tweaks.

First of all, they need to make sure that they have Python installed on their machine. And if they do, then they should be able to run the file. So before I actually type up a file, I want to show you that you have access to Python in the terminal. So if I type in Python Three, there’s a symbolic link that gets established when you download and install Python Three on your Mac. And I think it’s the same thing with Windows, but if you type in Python Three and you hit Enter, notice it brings up a Python command prompt. Now, in here, we’re actually in the python world, we can type Python commands. So if I was to define a variable called Tom and give him, hello, my name is Tom whatever. This variable has been assigned a sentence, and now I can print Tom. So you’re familiar with these commands. Notice it’s printing, hello, my name is Tom. So these are python commands. We can write loops and if l statements, everything. We can even create classes and functions and methods. You’ve seen that you have access to create all these things in this shell. But understand that when you close this shell, you lose the code, right? You lose the classes that you create, and you kind of have to start again. As a matter of fact, if I exit out of this shell exit out of this python shell. This is a python shell. I just type in exit and open and close parentheses. Like a function. It’s like a function call. I’m calling exit. And when I hit Enter, now all of a sudden, I’m outside of the python world, and I can access my operating system. By using Linux commands, you can also access the operating system within the python world.

Okay? So don’t think that you’re limited just because you’re in the python realm of things. You have access to doing many things in your operating system as well as access to the Internet. We’re going to get into those details later. So you have access to this shell. Now, if you were to create a file, and in that file you have some Python code, you can run it in the shell like this. Let me give you an example. I have a text editor that I’ve downloaded from the Internet, and it’s called Sublime Text. And so that’s what it looks like right here.

You can go ahead and search for this on Google. It’s a free text editor, and you can practice writing a variety of programming languages in this text editor. So we can choose right here on the top view, go to syntax, and we have all these different programming language options. So let’s choose the Python highlighting so that we can see Python. So here it is. We select Python, and now we can write Python code. So let’s say if I want to print hello there and save this file, let’s do save, and let’s save it in users Mt as a mod, basically in this directory in my home directory, and we’ll call this Greeting PY. Okay, let’s hit save. And now we’ve saved this file in that directory location.

And let’s close that file now inside of this command prompt or terminal, if I do an LS to list the contents of that directory, you’ll notice now we have this Greeting. PY file. Now, how do I run this file? Well, we can actually type python three and then specify Greeting PY like that, and hit Enter, and boom. There we go. Notice it says hello there. Pretty cool. So in that file. You can have all kinds of Python code and you can give this file to anybody, and they can run it on their machine as long as they have Python Three. Another way to do this, instead of writing Python Three on the terminal and then specifying the file, you can actually specify within the file that you’d like to use the Python interpreter to run the code. Let me give you an example.

Let’s open that file up again in our Sublime text. I’ll go to new window and let’s open as a matter of fact, let me just go to that file location in my directory structure here I go to users mt as a mod my home directory. And this is that file. So let’s just open it with Sublime text. If you right click here, notice there’s a default text editor on my machine. So I’ll move that right here. So another way to do this is on top of the file, I can specify that I’d like to use a Python interpreter, okay? And there is a special syntax for that. And the syntax goes like this. You put a pound sign and then you let me actually zoom in a bit so that you can see what I’m typing here. You put a pound sign and then use the exclamation point. And this is known as a shebang. Okay? And now we can specify what interpreter we’d like to use. All right, and so I’ve got Python Three installed on this machine.

And so the way to access that, especially in Linux or Mac, is you specify slash USR, slash bin, slash env, and you specify the Python Three program. Now a link has been made to this program. When you install Python Three on your machine, you should automatically have this link. If you don’t, I’ll show you another way to run this. So let’s save this file again. And now I can run this file from the command line directly without stating that it is a Python file. So let’s close this. And so this is our file. Now I can execute this file greeting PY by doing and then typing in Greeting PY. Now I don’t think it’s going to run just yet. If I hit enter notice it says Permission denied. Because when you create a raw executable file like this, you need to have permissions. So we have to give permissions to this file. And in Linux there’s a command called chmod. And I can just do seven, five, five and specify the file like that. And now we’ve changed. I think it’s seven, seven, seven sorry, I misspelled chmod. It’s supposed to be chmod. I put the O before the M there. So that’s a mistake. Seven, five, five and then you do Greeting PY and hit Enter. And now the permission for this file has been changed. And now we could just run it using a dot. This is a special notation on Linux to run any executable script.

And so let’s hit enter. And there we go. We’re able to run it like that. All right, so I showed you two ways. One, you use the python interpreter by typing in Python Three on the command prompt and then specifying the file. Or you treat it as just any executable file. And to run it, you have to make sure it has permissions to be run. And then you use dot slash, which is a Linux notation, to run any executable. And this file could have had python code in there, it could have had Perl, it could have had Bash, whatever. It would be the same way to run a script file, use a dot slash. Now, if I do Python Three and then specify the file, let’s see what happens. It still works.

So you have both ways. Now let me open that file once again, go to users, empty as a mod. Let’s open this file in Sublime text. If for whatever reason you got an error, then that means this symbolic link hasn’t been established on your machine. So you have to give the full path for Python Three. Okay? And a quick way to do that is if you just open PyCharm. Notice every time your program runs, it tells you where it’s running from. So you could just take this entire thing right here up to the word Python, copy that, and paste that in the script.

So let’s just replace that text, make sure you still have the shebang. You need the pound sign and the exclamation point, and you paste that like that. And this will also work. So let’s save it. Oops, I tried to save it in Linux. You just save the file and close it, and now it will run exactly the same way. So we do greeting PY python three Greeting PY. And there we go. Now you can have one script calling another script or utilizing a code that resides in another script. Okay? Essentially that’s what we’re doing here. When we created the machines class right here, vehicle stuff, right. We were importing this class in application PY and utilizing the code that was in there. Same thing with the utils package here, fold rather. And we have this util stuff file, I was importing it into application, running it. So similarly, you can have script files use other script files.

  1. Python Modules and Using Code from Other Files.

So you can have one script, one python script, call another python script, right? And that’s very simple to do in Python. So let’s define a file here and I’m just going to say let’s save this file, file save as and I’ll call this main underscore program and I’ll save this on my desktop to keep things simple, right? Main underscore program PY. So this is on my desktop and then I’m going to create another file and we’ll save this file as another file PY. Okay, so let’s say in another file PY, this particular script we have some code. Let’s define a function. We’ll call it greet user. And all this guy does is it prints hello there, stranger from another file PY. Okay, that’s all this code has. Now I can refer to this code in another file. So the way we do that is in the main program PY, we specify from another file import and you specify whatever it is that you want to import.

And what we want to import here is this greet user function. So that’s what we’ll do, greet user. And so now I can actually invoke greet user in this file. Okay, I’ll run this in just a moment, but let me tell you something. In this another file PY or in main program coming over to another file PY. We can have classes in here, we can have functions, we can have variables in this file. We can have all kinds of Python code. And we can import all of that code into this file by referring to it using the syntax from the file name. Import greet user. Now technically speaking, this is known as a module in Python. This particular what I titled here another file. This is known as a module and all the module is is a file that contains Python code. We’ll worry about the vocabulary in a little bit, but let’s make sure that this is working. All right, so now that I have this file, I’ll save both of these files, make sure and let’s close both of them. We’ll get back to that and let’s go back to our desktop.

And here is our two files, main program PY and another file PY. So let’s run our main program that calls this greet user function that’s coming from another file PY. And I can do that in the command line. So let’s just open up the command line. Let me expand this and let’s CD over to the desktop. And here is where I have all the files. So let’s run my main program PY. So we just do python three and then we specify main program PY. Okay, let’s run this. And there we go. Notice it says hello there, stranger from another file. So this message is coming from the other file. So similar to this inside of main program, we can reference many other files or modules.

Okay, now coming over to the vocabulary of how to name these things, specifically this main program PY, this file, it would be more correct to name it Main Module because that’s in python land. When you have a file that contains code, you should generally refer to it as a module. So that’s what we’re going to call it. So let’s rename this to main Module, okay? And the other one, another file PY. Let’s rename this as well to another module. Okay? And there we go. We rename this now, make sure that inside of mainmodule PY, let me open it up. It opens in my sublime text editor. I need to make sure instead of saying another file, I need to specify the name of that file. And that’s now another module, okay? The function name is still the same. So let’s save that and this will work exactly the same way. Let’s run it. So instead of python three main program, we now do python three mainmodul PY, and it works exactly the same way. Now, of course, I should have changed the text that gets displayed there, but that’s besides the point. That’s just a string. That’s what I typed there.

That’s what’s being printed, but it’s coming from the other module. So scripts, modules, think of them as the same thing. So we’re working towards building a program that contains multiple files, right? Because one way to write code is writing all of the code in one large file. And that’s no good. You want to organize your program into multiple files. And so typically your program must have various entities and various jobs that it needs to do. And so those jobs should be separated into separate responsibilities, and those responsibilities should be given to different files. So let’s say if you have a task that needs to, for example, download data from the Internet, well, the connection to the Internet, the download process, and saving the file into your computer, that should be a separate file. And then you can have that should be a separate module, right?

That should be responsible for that. And then another module could be responsible for actually reading the data and doing calculations and so on. So it’s better to break up your code like that into multiple modules or multiple files, rather than dumping all of the code in one file. Okay? So this is one way to do it. I introduced to you a new term called module in this lesson. And again, it’s very simple. All it is is a python file or python script with python code in it. That’s it. That’s a module. And that module can contain classes, it can contain variables, it can contain functions, you name it. You could put any python code in there. So this is one way of organizing your code where you have multiple files and it can all reside in one folder. In our case, both of the files are in desktop.

But when you get into writing larger programs, you have to get into this concept of packages, okay? Packages are basically folders in which there is Python code, all right? And you can have folders within folders within folders, sort of a nested structure. And we are actually already doing that here. Inside of this pie charm, we have these folders such as animals and machines. We were experimenting this stuff here. So these are essentially packages, except it’s missing one key element, and we’ll get into that shortly. It’s not displaying here in this file browser, but to create a package in Python. And again, a package is just a folder with Python files in it. Okay?