Python Part 21a - Classes - ID Card Make

Python Part 21a - Classes - ID Card Make So welcome to this wiseart tutorial on learning classes in python it's a biggie here's what you'll learn in the tutorial so we'll start with a look a few words about what you're going to learn managing your expectations really and then we're going to look at what classes are using our example of creating pet objects so i'm afraid annie and neo the cats are going to surface again we're then going to look at starting coding so we're going to look at creating objects in classes using something called instance attributes.

Python Part 21a - Classes

And at this point it's worth saying the rest of these contents may not mean a great deal to you at the moment they will do by the time you finish the tutorials so we're going to see a lot of buzzwords coming up we'll then look at more attributes so we'll look at creating values for attributes on the fly and also something called shared class attributes for objects we look at animating objects doing things to them using methods and then we'll look at class methods which are way of creating alternative ways to create objects it's called overloading in other languages.

We'll look at read-write properties in some detail so we'll look at what they are an example of what they are we'll look at how to actually create them simply and then we'll look at a full worked example we'll look at double underline methods such as underscore underscore str underscore underscore for documenting classes and finally we'll end with three thoughts on just how far you've come how far there is to go and what your next steps should be.

Most versions of the video a little icon should appear at the top right of the screen about now and you'll be able to click on that to go to our website to download any files or exercises to do with this tutorial but as is traditional at this point in the tutorial i'm going to vanish now and hand over control to sven it will guide you through the rest of this tutorial so let's get started it's a slightly pessimistic way to start a tutorial but i thought a word of warning is an order.

What i'm going to try to teach in this tutorial is a concept called object orientated programming oop which is just another way of implementing something called classes it's used in virtually all programming languages including c sharp c plus plus visual basic java and above all python but it's not that easy to learn and you'll probably find it takes you a year or two to get really used to the concepts so what better time to start learning than now along the way you'll learn about terms like attributes and methods and.

Inheritance and instances and constructors and polymorphism and namespaces and overloading and by the end your head will be spinning i would avoid tutorials which dive into the deep theory of classes and oop and instead i will concentrate on some practical examples you'll see two in this series of tutorials you'll see one in this one i'm working with pets and you'll see a slightly more complicated one on playing hangman in the next part of this tutorial series and what i'll do is make sure you're familiar with those and then.

Try creating your own very basic classes before you go into concepts like polymorphism or inheritance or any of the other scary words discussed on stack overflow anyway that's the end of my warning let's start with the practical learning so what we're going to do now is look at the building blocks of classes and there's two main ones i want to look at which are attributes which are the properties of any object and methods which are things you can do to it and.

These words will make more sense as we go through these series of points so let me introduce if i may to alfie who's my sister nor marie's new dog he's a whippet and alfie has three characteristics which i want to consider for the purposes of this tutorial which are his name his animal type which is dog and his color which is brown and white another pet is neo that's our cat and neo is called neo is a cat and it's black and white and the third pet is annie our other cat.

Bless her sitting there in a laundry basket and annie is called annie she's a cat too and she's taught a shell so we're going to create three attributes for our pet class and they are the name of the each pet the type of it what sort of animal it is and the color in addition to attributes you can also create methods things you do to it now an obvious thing to do to a cat like annie is to squirt her with a water pistol no only joking i'll never do that.

To any instead let's choose more acceptable methods and the one i'm going to focus on is one which writes out the details we've pet into a file so you can see there annie's details and to do that we'll create a save method and we'll pass in the name of the file in which the pet's details are saved so that's attributes and methods attributes are properties of a pet methods are things you can do to it there's one more concept we need to consider which is instantiation.

So whatever god you may believe in there's no doubt that he or she or it is capable of creating a pet like annie and at the point to which the pet is born or maybe at which you buy it that pet receives a name it has an animal type and it has a color so those are the attributes of it so when you instantiate an object you use an underlying template which are the rule properties and methods or attributes and methods defined in the underlying class to create a new object based on those rules welcome to object orientated programming.

And i think with all that in mind it's time to create some practical examples in python so to begin with what we're going to do is create the most basic class you can get i think and to do that you type in the word class and then you put the name of your class and by convention only you tend to use capital letters for the names of classes so i've called my pet although this symbol here looks a little bit like a pet it's actually just a flow diagram i think rather disappointingly and to make sure that my class is accepted i need to do something.

Posts Related:

    Within it and the word pass is just a filler to make sure that it completes the syntax - ID Card Make

    So what i'm now going to do is create a new cat or a new pet and to do that i'll call my new pet annie cat and i will use the word pet to create a new pet but you need to put open and close brackets around it past it for reasons which i hope will become apparent as we go through the tutorial and i'll create another new pair called neo so now let's try printing those out.

    To see what happens we shouldn't really be expecting very much from this because i haven't actually created anything i haven't given them names or animal types or colors it would be a bit unreasonable to think what you're going to get in fact it's not clear we'll get anything at all let's try running it and what you'll see is all you get is the memory address of where each object is based so what this line is saying is hey i've created an object for you it's of type pet that's the class it's based on and i'm storing it to this memory.

    Address but that's all you've got available okay so let's make this more interesting by adding in some instance attributes what we're going to do within our class is create a function with the special name of init and when you press tab irritatingly visual studio code does a habit of in completing that for you which i personally don't like so let's go back to where we were so we need to pass in three bits of information the name of the cat.

    The animal type and the color spelt apologies for this americans the english way and you could if you like specify that this returns none but people tend not to bother because an initialization routine wouldn't really return anything anyway and then i need to put something in that to make it work so now when i create a new pet and let's just stick to annie for the moment i need to specify the details because if i miss them out i will get a.

    Mismatch between the arguments the initialization routine is expecting and the ones i'm providing so it looks to me like i need to specify three bits of strings three strings the name of the animal the type of it and what sort of color it is from everything we've seen in python so far that should be sufficient but if i run that program it will give me an error message and it says it takes three positional arguments before we're given.

    So it takes three positional arguments i gave four how did i give four well the answer is when you create an or instantiate an object based on a class automatically the initialization routine has an extra variable which you need to capture an extra argument which is something to refer to the class itself and traditionally this something is called self it doesn't have to be you could call it archibald if you wanted to but normally.

    People call itself and i think it'll just confuse other programmers if you don't do that and the reason that's a useful thing to have is because within your class you need to now give it a memory okay you've created a pet and you said here's what it's called and what animal type and what color it is but when you come to ask the class in the future what was your name what animal type were you what color were you it won't have a memory to give it a memory you create instance attributes.

    So the first one we'll create is going to be called name which by coincidence and it is just coincidence is the same thing we called our first argument and we'll set the name property of this object to be the name we passed in so what that does is is take the name annie which we're setting to be the name of our new pet and storing that internally within the class and if you can understand that you're well on the way to understanding classes because that's probably the weirdest thing about them.

    We need to repeat the trick creating two new instance attributes so we'll create the animal attribute to hold the name of the animal or the type of the animal and finally we'll create the color to hold the color your notice is not auto completing because at this stage the attribute i'm creating doesn't yet exist it's only when i type that in that it automatically creates this as an attribute of the class okay so when i run this program it should work it doesn't actually do anything because.

    I'm not printing anything else so what i'm going to do is print out some details and to do this i'm going to print out

    Any cat when i type the dot in it will come up i thought it would come up with all the attributes of the class so i'm going to print out the name of the particular pet and i'll print out its color and that you can see it gives me that annie's a tortoise shell.

    So what i'd like to do now is to show a bit more about attributes we're going to cover two things instance attributes created on the fly i think that's my term not an official one and class attributes and this will hopefully become clear in a moment so i've modified my file called creating pet stop py to create three new pets not just one i've got alfie near and annie and the first thing i'm going to do is actually put them in the list and print out the contents of the list so i'm going to put the pets in a list and print so to do this i will create a.

    New variable called pets and i'll set it to be a list containing different objects alfie neo and annie in that order and then i'll print each one out by saying for each item in the list then i'll print out i won't print out the object itself because that would just give me the address memory address of where it's stored instead i'll print out some interesting attribute of it and what could be more interesting than the name of the pet so if i then run that program you'll see it will give me alfie at neo and annie just a quick word.

    About naming conventions i've used the word pet to refer to each of the pet objects in turn this is a good practice i would say don't forget python is case sensitive and because classes always begin with a capital letter by convention you're fairly safe referring to each object in that collection by the lowercase version of the name because there'll be no conflict so what i can now do is add a new variable for one of the pets so what i'm going to do is say that um neo has four legs now that's a fairly.

    In fact i won't i'll say alfie has four legs this is true by the way he's a whippet he wouldn't get very far without them so i'm going to take the variable called alfie which refers to a pet object and refer to the legs attribute how can this be there isn't a legs attribute i didn't add it when i initialized the object based on the class but you can create attributes on the fly like this when you do this each don't forget each of the separate objects you create is completely.

    Isolated from all the others so by adding a legs attribute to the alfie object you make no effect whatsoever on the neo and the annie ones and i can prove this i'm going to go down to my loop and i'm going to also print out the legs now when you run this for alfie it will try to print out the name of the pet and its number of legs and because i've added that as an instance attribute on the flyer like that that will work but for the second pair neo it will try to reference a legs attribute which.

    Doesn't actually exist for that pet and it will crash so let's see if this works and that's what i predicted and there it is the first one works fine but the second one it points out that neo doesn't have an attribute called legs so that's creating an attribute on the fly you can also create something called a class attribute to see how this works they are deceptively simple what we're going to do is assume that in a moment we want to save each of these pets to a file and so what i'm going to do is store the.

    File path of where i'm saving it in essentially a global variable except as we'll see in the second it actually isn't so i'm going to save it in the variable called wisel backslash pets or rather the path and what i could then do is i could show this in my loop so i could show the file path and i'm going to need to take out the legs because we know that we'll crash it so if i run this you'll get the name is.

    Different for each object but the file path is always the same my advice to you is when you create a class attribute like this assume it can't be changed which is actually fairly close to the truth and you could stop watching this small part of the tutorial now but what i'm now going to do is show you very briefly what's actually going on when you try to change it okay so this is maybe for this next 30 seconds to a minute is maybe for.

    People who are comfortable with what they've learned so far and want to know a bit more about it let's suppose for the alfie example i i won't specify he's got four legs but what i do will do is change the file path and i'll change the file path for neo so to do this i can set neo's file path and i'll change it to something slightly different from what it was before so let's change it to pets too.

    When i print this out you can see i get a different file path for neo and the obvious temptation to think is that's behaving like any other attribute i've got an attribute fold called file path i'm setting it for each of the different objects it's set to a different value for neo and when i print them out that's why i get a different result but that's actually not quite what's going on what's going on is when you type in this line what it will do is create another instance attribute for neo called file.

    Path so neo now has two different attributes it has a class attribute whose value never changes and then it has an instant attribute you've created on the fly containing the the different path when it comes to this line and tries to print out the file path for alfie and annie it has no problem there's only one version of that attribute the class attribute and that's what it prints out when it comes to neo there's two separate attributes called file underscore path.

    There's a class one and there's the instance one created on the fly and the rule is with python that when it's resolving references like this it looks first for instance attributes and only then would it look for class attributes so although this looks like it's printing out the value of this class attribute up here it's doing no such thing it's actually printing out the value of the instance attribute there now all of this is so confusing that the best thing to do is pretend it actually doesn't have is impossible and can't work like that so what i would strongly.

    Recommend doing is not changing class attributes and assuming that they are fixed and can't be altered so just before i begin covering methods just a bit of housekeeping i've taken my original file and renamed it as attributes.py and taken a copy of it and renamed the new one as methods.py from this i've deleted some of the extra commented out text we had in so it basically just has a class in including the class attribute giving the file path i'm going to save to and the code to create three new pets.

    And then list out their details and if i run that program you can see it gives me the basic details what i'm now going to do is to write an additional program within this to save each pet and to do this what it will do is go to um a folder called wiser backslash pets go to a file called pets.txt and write out another line in this file i put some headings in to get us started so for each line you'll get the name of the pair comma the animal type comma and.

    Then its color okay so get to get this to work then the first thing i need to do is to create a new method and methods are just functions contained within a class so i'll call my method save and the only real difference between this and a normal function is you need to pass in as a first argument a reference to the class itself just like we did for the initialization method above and again you could call this argument anything you like but by convention it's always called self.

    The other arguments can be anything i like i'm just going to have one which is the file name i'm going to save to so you can save different pets to different files and that will be a string of text that's the end of my method what i can now do is to open up a file into which i'm going to write out the details file for writing and to do this i can say with open i want to refer to the file path above but when i type in a file underscore path it's never heard of it and that's because the file path is contained.

    Within the class so you have to get used to preceding virtually everything when you're writing class modules with or rather instance modules with the word self so i'll now concatenate onto that the file name except i don't need the word self in front of that because that's being passed as an as an argument to my method so with that i'll specify the second argument so i'm going to append onto the end of it.

    And i'll call this um pet file with that what i can now do is write out the pet's details so to do this i can say pet file dot write and i'll write out the details so i'm just going to write out the three bits of information and i'll use placeholders to refer to each one substituting the things i want to put in so i'll put in the name of the animal as the first bit.

    The animal type as the second and the color as the third that's my method what i now want to do is to be able to call it so leaping over the pets what i'm going to do is instead of um actually printing out the name of the pet i'm just going to save it so to do that i can put pet.save and when you type in the open brackets it will always ignore the first argument which is always assumed to refer to the current object and just pick up on the.

    Other ones so i need to specify in this argument the name of the file i'm going to use i'm actually going to save them all to the same file called pets.txt now just before i run this i just noticed i made two mistakes easily done that should have been a curly bracket and also i could do with putting in a carriage return after each line otherwise they're just going to all accumulate on the same line okay so let's try running this if i run my program nothing seems to have happened that's probably a good sign and if i go.

    To my file and double click on it you can see it's written out the details of my three pets so that's how you can create methods they're just like functions the main distinction is you include as a first argument a reference to the object itself so to explain class methods what i'd like to do is explain the problem i'm trying to solve we've got a file called pets.txt and if you go into it you'll see it contains three pets.

    And what i would like to do is to use this file to create my new pets and the reason this be difficult is all i've got now is a line of text whereas previously i had the three bits of information the name the animal type and the color of three separate items so to get this to work what i'd like to do is to go back to my code i'll just comment out what i had before and create a variable called pets to hold a list of all my pets which i'm going to read in and then i'd like to say.

    With this file but it's called i'll read it in that's the default anyway i'll call that pepfile and then with that file what i'm going to do is read in all but the first line put a variable called lines and set that equal to the pep file i'll read in the entire contents of it i'll split those into different lines and from that i will take everything but.

    The first line then i can loop over the lines i can come in for that create pet from each line so to do that to do that i can say four line in lines what i would like to do is to create a new pet at this point so to prove what's going on before i do that i'll just print out the line and run the code just to prove that's working and you can see it's giving me my three lines of text.

    So what i'd like to do is to create a new pet and add it to list this is where i'm going to run into a brick wall to create a new pet i know how to do that i provide the string sorry the name of the animal as a string of text the animal type and the color but i don't have that information all i've got is a single line of text now what i'm going to do something quite unusual at this point in the tutorial i'm just going to show you how this works in c sharp so if i go into c sharp i've got here.

    Two constructors for a class don't worry about the syntax i just want to illustrate the principle so i'm creating a pet there in a very familiar way from python by specifying the name the animal type and the color but i've got a second constructor as they're called that's what um programs to initiate initialize or instantiate a class are called in c sharp and in most other languages and the second constructor just takes in a single line of text and splits that into the three parts and uses that to populate the glass.

    Now when i come to call this and create another pet watch what happens so i'm going to create a new pet using my c-sharp class and when i type an open brackets in it comes up with these little arrows this is called an instance of anyway of polymorphism it means there's different ways to do the same thing so i can either do it by specifying just a line of text or i can specify the full caboodle the name the animal type and the color either will work.

    That's what i want to do in python which i need to go back to because i don't want to confuse you with c sharp i need to provide an alternative way to create a pet so i need to go back up to my class at the top here and in addition to my standard initiat standard initialization routine or instantiation routine i need to create another function which will instantiate a pet in a different way so instead of passing in three arguments it will just pass in one which is the line of text.

    DISCLAIMER: In this description contains affiliate links, which means that if you click on one of the product links, I'll receive a small commission. This helps support the channel and allows us to continuetomake videos like this. All Content Responsibility lies with the Channel Producer. For Download, see The Author's channel. The content of this Post was transcribed from the Channel: https://www.youtube.com/watch?v=RfLDsAqtr7k
Previous Post Next Post