Everything you need to know about Classes in Python! (Object Oriented Programming Tutorial)

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
hey what's up guys and girls and welcome back to another video today we are going to be talking about glasses sorry classes no classes there we go classes and more generally object-oriented programming is fundamental to becoming any sort of software engineer whether you want to be a data scientist a mobile app developer a back-end engineer you're gonna need to know about classes in this video we will start with the basics what our class is how can we define them in Python when and why should we use them and as we go throughout the video we'll build up some more advanced concepts you know we'll talk about sub classing we'll talk about operator overloading and I'm gonna try to make it very visual so you can really drill down these concepts quickly and efficiently before I begin I want to give a quick shout out to this video sponsor and that is kite kite is a machine learning based code completion tool for Python that works with all of the most popular editors like atom vs code sublime vim and pycharm kite up to code faster by giving you all sorts of code completion suggestions sorted by relevance and it can give you completions that are up to full lines of code which is really cool if you're interested in checking out kite I left a link in the description I have been playing around with kite for about a month now and I've had a very very good experience it's super fun and it has made me code faster one of the best parts I forgot to mention is it is completely free to download so definitely check out that link in the description but without further ado let's get into this video to start off I want to give a little bit of background on why we should use classes so when I was at MIT we had a model that if you wanted to write good code it should be safe from bugs easy to understand and ready for change in classes and object-oriented programming really hit on these three points they make our code safe from bugs by allowing us to kind of isolate the different parts of our system we can easily write test cases for one specific class while abstracting away the details of the other dependencies they make our code easy to understand by providing structure to our code we can group all of the variables and methods that kind of share an object and functionality together and separate objects from one another and then they make our code ready for we can easily add new class methods to existing objects and if we ever need to provide completely new functionality we can always make a new object while kind of not screwing up anything else we've already written I can only teach you so much though by telling you all of this let's start writing some code so you can really get a hang of it yourself I'll be using Python 3 and sublime text as my editor and let's start off by writing our first class and I want this visit this tutorial to be very visual so I'm gonna be using shapes as kind of my example to start off so let's define a class called polygon and so the convention to do this is class and then usually you define your class with a capital letter so we have this polygon class so polygons triangles squares Pentagon's hexagons etc that's what we're gonna be defining with this class so to start off when we define a polygon we define it with a certain number of sides and a name or something so when we initialize stuff in a class we always use this convention and it might seem a little bit weird at first but you'll see throughout this tutorial why it's useful so we do def in it and then the first parameter we always pass in to our knit method is self and then we need to think about what's important to a polygon well maybe the number of sides is important whether you know you have four sides in our square or if you five sides in our Pentagon and maybe we want to give it a name too so we define our polygon Hutton's by the number of sides and the name and the last step whenever initializing things and this will not make sense at first but as I go through it will make sense we do self dot sides equals sides and self dot name equals name okay with that we've defined our first class let's see a couple examples of us using this class in action so I'm going to start off by defining a square which is equal to a polygon and based on what we set in this knit we will have to pass in sides a name so to define a polygon we'll have to pass in the sides and so let's define a square that has four sides and then we'll give it the name and let's also define a Pentagon so Pentagon is a polygon with five sides and the name Pentagon cool cool and now what we can do is I can do print square dot sides and as you can see it says four down here I can do print square dot name and it says square so we've basically what's happened is by feeding in these parameters 4 and square we have passed in we have created a polygon class and when we pass these in we set the sides and we set the name through this in it method and as you can see with Pentagon pentagons both sides and then we can do a print Pentagon dot name the same thing is true for the Pentagon so we've captured we've kind of encapsulated the information through this polygon class of a square and a Pentagon and to quickly clarify the only things we need to pass into our method so when we're initializing the polygon is the stuff after this this the stuff after self the sides a name I'm gonna get to self in a little bit in this video but just keep in mind that when you're creating these objects you just have to worry about the stuff after self now it's cool to be able to see all this information about the classes we've initialized but let's move on and do something actually cooler and that's actually draw the shapes based on the parameters we pass into the class so to do that we can define a class method so I'm gonna define a class method called draw and normally wanted to find a method if I don't need to pass in any variables we can just do it like this draw and you know and you know into the functionality here as we need to but because this is a class method the first thing that we're gonna want to do is pass in self to this method and we're gonna slowly start building up what self is but basically we have these properties in our class sides and name we pass itself to our class method to allow us to access these parameters without having to like mainly type in sides name every time you want to use this function so we can just access them by passing in self and this will make sense in a sec and also we need a way to actually draw the polygon so to do that let's import the turtle library it's a nice easy visual library for Python and something cool I mentioned I don't know if you just saw the right side of my screen but I'm currently using kite copilot and something that's really cool about it is that it tracks my cursor location on the screen and can tell me all sorts of documentation about where I'm at in the code which is very very nice and if you know my videos I'm always dragging in Google searches for documentation so this is a really useful feature for me to kind of like know that mutation as I write the code okay so we're gonna import the turtle library and we want to draw our shape so the way we can think about it is we need a for loop for each side in our shape and let's think of these as regular polygons so they each have the same size so to find this draw method we'll can do something like for I in range self dot sides so we're getting whatever number we passed in here and then we're going to want to go turtle dot forward we'll say let's say maybe a hundred hundred pixels and then turtle dot hmm now we need to turn a specific angle so if we're doing a square we would need to do like turtle dot right ninety degrees and as you can see we have to pass in the angle to this function turtle dot right 90 degrees this would allow us to do a square but we need to be able to do this for any sheep we pass in so we'll have to probably edit our own it method a bit to give us an angle to well let's just start with seeing what a square would look like and I'm gonna just end this method with a turtle dot done I might end up putting this somewhere else but for now we'll leave it here okay so now let's go ahead and do square dot draw and see what happens look at that we just drew a square using the turtle library that's pretty cool okay so we knew we had to turn right 90 degrees for a square but let's abstract this away and make it more general generalizable so we can do any shape using this right method so if you dig back into your high school geometry days you might know the formula for interior angles of polygons but if you don't here's a helpful little chart we can use to kind of get the details on what our values are going to be so the sum of interior angles of a triangle is 180 the sum of a square is 360 540 etc and the general formula for any polygon is n minus 2 where n is the number of sides times 180 degrees and then if we want a specific angle and that's what we do one in our case it's n minus 2 times 180 divided by the number of sides because if you have a total of 360 degrees four sides each angle has to be 90 degrees and that's the interior angles here so let's start writing some logic into our class that captures that so we could define a poly Oh polygon interior angles property that is equal to well it's going to be equal to the number of sides that was the end part minus two and we're going to put this in parentheses times 180 right that was the interior angle sum so you can maybe define this like sum of angles and tiri angles whatever you want so that would be the all the angles if we wanted just the individual angle it's going to be equal to self dot interior angles divided by self dot sides and now we have to find two more properties of our class and these ones are computed on initialisation so it doesn't matter it depends on what number of sides we pass in so let's see that now in action if I do go back to what we were printing out before and I did print square dot let's say interior angles and I did print square dot angle this should give me 360 and this should give me 90 let's see if it does look at that 360 and 90 cool cool okay and now what we can do is pass in that angle here so we can do self dot angle because we can use the self method or the self parameter that we passed into our class method to access the self dongle that we initialized on the creation of our class to turn right 90 degrees okay cool so let's see if now with passing in this we get the same result of that draw method so we're going to do square draw and notice I don't have to pass in self here which might seem a little bit strange self is the one thing that's kind of just known to be there so whenever you see self you kind of think about you don't have to include anything there you just skip it it's like it's not there when you're actually trying to define to utilize a method you just use what it's after yourself so like when we initialize the polygons we initialize the stuff after yourself and when we use draw even though their self in it we don't have to pass anything in it that's a little weird at first but it should make sense over time so let's do square draw look we get that same square all right real test will be though does it work with Pentagon draw come on draw Pentagon ah no why did it not work so when we're doing turtle dot right we're defining this exterior angle so this right now is what we defined by self dot angle but we really want it to be this interior angle so do compensate for that we're gonna just need to take the complement so if this interior angle here should be 108 we need to do 108 or 180 minus 108 on the outside so we can actually define when we do the right method we can do 180 minus self dot angle and that should be give us the right result look at that got it cool all right and let's check to see if it works with like maybe a hexagon let's just make sure that it's actually working properly so I can do a hexagon equals polygon and that's gonna have six sides and I'll call it hexagon it's good and now let's do hexagon dot draw look at that it's calculating those angles correctly that's pretty sweet one thing I think it would be nice to do is right now we're passing in a hundred always here we could pass this in as another variable to our polygon and so we'll do size and we'll say self dot size equals size so now when we define these we have to pass in like 100 here if we don't pass in 100 see what happens it gives me this long error and ultimately this is the important part of the air it's missing their one required positional argument sighs so it's airing out because we didn't pass in size and we included that in the init method so it doesn't know what to do so we can pass in 100 here and 100 here and that would like allow us to define those properly we're gonna get the error again down here so let's say we wanted to find it that's 10 to start and we've passed now in our draw method we should do self dot size instead of 100 so let's see what happens look at that it's 10 is a little tiny hexagon and if we did 100 should be a bigger hexagon and it is cool cool but maybe it's like annoying too you can imagine we could just keep building out the number of parameters we want to pass into our polygons and would be annoying to have to like include every single one when we define our classes so what we can do is the same as we can do with functions is we can give it a default argument so let's say our default argument is 100 so now I can define it without these parameters and do it for all three and now it won't error out on me because it'll just know that if I don't provide this size it will default it to 100 so watch what happens when we draw the hexagon see it's the normal big hexagon so if I go ahead and make that 10 here it will override that default value of 100 and allow us to draw it at size 10 and it works cool and you can imagine where you start getting fancy with the type of things we pass in here so maybe we also want to be able to provide a color for our polygons so let's say the default color is black we can use turtle then this is just something I know about turtle that it accepts where it's like that I could do turtle dot color is self dot color and I need to define self dot color here and now it will draw the shape based on the color we select so we have black line there and if I wanted to do a different color I could pass in I can either pass in both the size and the color or I could just define that I want the color to equal let's say red and as you see it's red and you can imagine I could you know maybe pass in the thickness to so thick line thickness that's going to equal let's say like two pixels to start by default and within turtle I think there's a way to set the line thickness turtle dot let's see if we can use a lot utilize this documentation what other things screen choice and look at this all this documentation does a lot of helpful things pen size that seems good to me so I can do turtle dot pen size and probably pass in self dot size let's see what happens when I draw oh my god what is that what is the size of this oh my god Oh oops I did self dot size here instead of self dot a line thickness okay so I'm going to pass in self line thickness equals line thickness that was a clacks classic mix-up okay and now we could pass in you know maybe it would make three the default value and I think this is in pixels but if we wanted a really thick hexagon I could pass in you know line thickness equals twenty and as you see you get a thicker polygon so we can do all sorts of cool stuff but maybe we just want the tie to fall to just have to pass in the you know number of sides in the name just to drill down a point on what the heck self is let's imagine we had to write this draw method outside of the outside of a function so we could do let's define draw function so in this we needed a color we need a thickness we need sides we need size we need an angle so we need a bunch of parameters so I could say sides size angle line thickness and color all is parameters to the function and then I could basically copy and paste this in and now instead of you know self we do this you know we're not using stuff anymore we're using these parameters you passed in and you know this still works so we could still call instead of doing draw down here we could call something like draw function five sides size 20 angle I guess this is now not pre computed so I don't have to figure out the angle will would be 108 I guess line thickness for color red we can do this and it's still gonna work for us the thing is it's just really annoying not being middle to utilize like something we've already kind of predefined pre computed some things it just makes our life more difficult to not use the class method so self is really helping us by allowing us to access all these things that we initialize at the creation of our class and a nice succinct manner all right we can delete this because I was just using it as an example and also I'm gonna have all this code on my github page and that's link to in the description but for the time being I'm going to just delete some of this stuff to kind of make the code a little bit cleaner for now all right the next topic we're going to talk about is the concept of inheritance and specifically we're gonna be talking about sub classing so let's say that we wanted to define a class that was specifically a square but we didn't want to have to rewrite a lot of this logic to draw a square and you know would you define the number of sides of what not a square has we can utilize this polygon it's kind of the parent class and make a subclass called square that utilizes it so we can do class square and that's going to be a subclass of polygon so we have the past polygons to specify that square is utilizing polygons and what we can do now is we can define it an it method for the square so we can say something like definite just like we did before we're gonna pass itself like we always do and if we want we can pass in all these same parameters or actually we and then we're going to decide what parameters we have to pass in well for a square we know that the sides is only going to be forced we don't need to pass that in each time we define a square we notice you may call to square so we don't need to pass that in so we can just utilize these last three parameters and pass those in and then to specify that these always have four sides and always are called squares we can use the super method in Python so we can do super and that's basically say saying take from polygon anything from the parent class the superclass we're gonna utilize it using this super method and when you do super dot an it so we're getting the initialization method from polygon and we're gonna pass in four for the number of sides we're gonna pass in the name square and then we're gonna pass in all the other stuff so size color line thickness etc okay and now we've initialized that so one thing that's really cool is just by utilizing this now we can define a square and get access to all the properties that we normally have in our polygon so let's define a square so square equals square now and I can just do that I don't have to pass in the number of sides or the name anymore because we're creating a subclass of polygon called square and does that give us an error it doesn't give us an error and watch we can even use like squared out sides we can print this out and we can print out let's say squared angle so this should be 90 so it should be four sides and angle 90 and look at that just this thing utilize the initialization method of the parent class and we were able to get the angles and you know define the sides through this so this is kind of a neat little trick and subclassing allows us to like get very complex with our code because we can create these structures that reuse code instead of having to rewrite it from scratch so subclassing allows us to you know really utilize previously written code and not get too verbose and you know rewrite things we've already written so if we have a mistake one spot usually fixing it in that one spot we'll fix it all around so this is a nice little thing about sub classing and to drive this point home we could even use square draw and get access to that from the initialization method and from this being a subclass so squared out draw look at that we got a square and if I wanted to I could pass in you know like color equals let's say we wanted hexadecimal colors of 1 2 3 ABC I don't know what color this will be we'll find out so that gives us some sort of blue we could pass in you know a but try to pass in sides equal 5 see what happens and it's going to give us an error because that's not a part of the initialization method of the square so it's kind of nice it keeps people from trying to like trick the system and to find a polygon with sides four of a name like Pentagon let's say do size equals 200 big big big square cool this is awesome another useful thing to know about sub classing is method overriding so let's say we wanted to take the polygon draw method and do a little bit more to it so we can actually do in our subclass is override that draw method so we can do ja def draw self and maybe we wanted to fill in not only color it based like like this but actually fill in that color I'm gonna do turtle dot begin Phil this is just a turtle method you're gonna watch my video on tutorial on turtle if you want to know all about it turtle about begin Phil and then we're gonna use super dot draw so we're going to copy and paste basically the code from up here in the middle and then turtle dot and Phil and just because I know that we're gonna get a problem because I left this turtle down in here I'm gonna remove this from the function and actually put turtle dot on down here and that just keeps my screen open when I'm done drawing so let's see what happens now when I do turtle dot or begin Phil look at that we surrounded the normal method the draw method from here basically we used it in our sub class and added a begin fill in an end fill and now we get some like extra functionality which is pretty cool okay that will cover sub classing let's move on to another example that will cover a couple more concepts with classes before we end this video in this example we're going to define a point class that we'll use to cover a couple different concepts so to find that we can start by doing class point and we'll need to initialize some things for this and so anytime we define a point we can think of these as being two-dimensional points so we need an x and a y I'm just going to set them like this self dot x equals x and self dot y equals y and I can go ahead and write there where you have a point class I can say ay or like let's say point one equals point four five and if I did point print point one dot X we'll get an error I don't know what I did here what did I do oh we got a pass himself there we go and we get four cool so the next thing you might want to add to a point class is maybe we want some way to plot this point to do that we'll import matplotlib and we will do the following so we'll define a point dot plot so def plot that will just take itself and we can do a plot dot scatter I think we can just pass in self dot X self dot Y here and I think if we just do that let's see what happens so I'll say a equals point three for a dot plot and then I think we have to do plot dot show and actually see a graph and we got a point right there cool ok so we have a point and we can plot the point that's cool what if we wanted to do something fancy let's say we define two points so we have one point that's one one and we'll define B as the point two two so let's say we wanted to be able to make a third point C that was equal to a plus B let's see what happens when we try to run that and it gives us an error what is our error well it says unsupported operand types four plus point end point so it doesn't know how to add this point class that we defined so this gets us into the concept of operator overloading so we can actually override the default like plus for the point class and so we can actually make it know how to add a plus B even though it's not like a built-in Python type so to do that we can define another kind of special type in the class called under underscore add so it has a similar syntax to the unit and it we can do self comma other so basically if we imagine that the other is a point type if we do cell or like x equals self dot X plus other x and y equals self dot y plus other dot Y so this is assuming other is another point then we can return a new point which is these new coordinates x and y so X is being the addition of these and Y being the addition of these so let's see if that works no errors so the moment of truth comes when we try to print out something part of C so C dot Y and C dot X should both be three and is that the case look at that three and three looks good and real quick I think it's useful to see we can overload all sorts of different operators in Python so we just over rode the add operator we can overload tons of different stuff so I'm gonna bring in a helpful little cheat sheet and I'll post this in the description of the video but as you can see you know you got the binary operators we can do all sorts of stuff division for division modular we can do greater than signs greater than or equal greater than or equal to signs all sorts of interesting stuff here and this is only like a sub list of everything that you can actually do building on this let's say I wanted to do maybe we'll change up our points so instead of doing a and B we'll do we'll just define a as being maybe zero two and let's say we wanted to create a new point I'm going to just call this point D which is equal to a plus 5 well 5 is now no longer a point so if I try to do this what did I do if I try to do this we're gonna get an error and into object has no attribute X so it like can't do this command so we can account for this we can allow ourselves to add different types to the point class so what we're gonna do to handle this is we will say if is instance and we're going to pass in other and if it's an instance of the point class this is how we use it let's check the documentation for his instance so it's the object and then I think the type so if is instance object of point class then we want to do this LF maybe honestly we can just kind of encapsulate all the additions in the else case we can say X equals self dot X plus other and y equals self dot y plus other so the reason I left it as else is I wanted to be able to handle not only intz that we're adding to it but maybe floats so like decimal numbers in addition to energy numbers and then we will want to return a point of XY just like we did in the above case so let's see what happens now if we do a plus five didn't give us an error does it work do X so it should be five here and D dot y should be seven so let's print that out real quick let's see if it works look at that and if we go ahead and actually add another point to this we can see that it still works with the original code so let's say point one one see we can now add two different types so that's pretty cool with the operator overloading alright we're going to end this video here hopefully you guys feel like you learned the basics of classes and kind of how you can use them effectively I couldn't cover everything about classes in single video so if there's certain things you feel like I left out let me know in the comments so that I can include them in a future video if you enjoyed this video make sure to throw it a big thumbs up and also if you haven't already hit that subscribe button and then the final thing I want to say before I go is if you thought kite was cool throughout this video make sure to check it out the link is in the description thank you again guys for watching until next time Purcell [Music]
Info
Channel: Keith Galli
Views: 86,385
Rating: 4.9492908 out of 5
Keywords: MIT, classes, class, python class, python 3, python programming, object oriented programming, oop, objects python, inheritance, subclassing, classes in python, simple classes tutorial, decorators python, operator overloading, simple tutorial, classes tutorial python, what is self, self python, classs, object orient programming, oop python, python oop tutorial, how to use classes in python, why use classes, python 3.8, basic python, easy, beginner python, python fundamentals
Id: tmY6FEF8f1o
Channel Id: undefined
Length: 33min 48sec (2028 seconds)
Published: Sat Feb 29 2020
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.