Python OOP Tutorial 3: classmethods and staticmethods

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
hey everybody how's it going in our last video we looked at the difference between instance variables and class variables and in this video we'll be learning about the difference between regular methods class methods and static methods and a lot of people get confused as to the difference between class methods and static methods so we'll definitely go over that in detail so as we learned in our previous videos regular methods in a class automatically take the instance as the first argument and by convention we were calling this self so if a regular method automatically takes in the instance as the first argument then how can we change this so that it instead automatically takes the class as the first argument now to do that we're going to use class methods and to turn a regular method into a class method it's as easy as adding a decorator to the top called class method so let's go ahead and create one of these so I'm going to create a new method here with that class method decorator and I'm just going to call this set raised amount now for this set raised amount method I'm going to take in the class and I'm going to take in an amount and for now we'll just put in a pass statement there now if you'd like to learn more about how decorators work then you can watch my video that goes into that in depth but basically this is altering the functionality of our method to where now we receive the class as our first argument instead of the instance now by convention with a regular method we called this instance variable self and there's a common convention for class variables too and that is CLS now we can't use the word class as the variable name here because the word has a different meaning within the language you can see here at up at the top that we use the word class to create a new class so that is a keyword in Python so instead we're going to use CLS as our class variable name so now within this set raise amount method we are working with the class instead of the instance and to show you what I mean by this let's go ahead and set our class variable raise amount so we'll say class dot raise amount and we'll just set this equal to the amount argument that we are accepting from this method so now down here at the bottom I still have these two employee instances that I created in our previous tutorials and Here I am printing out the classes raised amount as well as both instances raised amounts so if I go ahead and run this then you can see that all of those are equal to 4% now the reason all those are equal to 4 percent again is because we have this class variable here raised amount that is set to 4% so now let's say that we wanted to change this to 5% so before I print these out then I could just use that raised set raise amount method that we just created and I could do employee dot set raise amount and it automatically accepts the class so we don't have to pass that in so now we can just pass in an amount so I'm going to go ahead and do 5% and if I save that and run it and you can see that now all of these are equal to 5% now the reason all those are equal to 5% is because we ran this set raise amount method which is a class method which means that now we are working with the class instead of the instance and we're setting that class variable raise amount equal to the amount that we passed in here which is 5% so really us running this set raise amount method here and setting this CLS variable raise amount to the amount is the same thing as us saying employee dot raise amount equals 5% but now we are using this class method to do that instead now you can run class methods from instances as well but that doesn't really make a lot of sense and I don't ever see people doing it but to show you what that would look like I can also grab this instance here and I can run that class method from the instance and if I run that you can see that running that class method from the instance still changes that class variable and sets all of the class variable and both instance amounts to that 5 percent that we passed in now you may also hear people say that they use class methods as alternative constructors now what do they mean by this so what they mean is that you can use these class methods in order to provide multiple ways of creating our objects so let's say that for example we had someone who is using our employee class and they said hey I have these specific use cases where I'm getting employee information in the form of a string that is separated by hyphens and I'm constantly needing to parse the string before I create new employees so is there a way to just pass in a string and create an employee from that so let's go ahead I have an example down here to where we can see exactly what this problem would look like so let's say that this is a common use case for how someone is using our class we have three strings here that are employees separated by hyphens so we have the first name the last name and the salary and they're all in a string and they're separated by hyphens now if I wanted to create a new employee from this string then what I would have to first do is I would have to split this string on the - and then we'd have our first name last name and our pay and then based on those values we would be able to create a new employee by passing in those values and that would run our a knit method so now let me go ahead and save this and run it and you can see that this works we're splitting the string up into a first name last name and pay and then we are creating a new employee just like we did up here out of those values that we parse from the string and you can see that it works because we're printing out that new employees email and pay and everything is as it should be but if this is a common use case for how someone is using our class and we don't want them to have to parse these strings every time that they want to create a new employee so let's just create an alternative constructor that allows them to pass in the string and we can create the employee for them so I'm going to go ahead and come up here and create a new class method and we're going to use this new method as an alternative constructor and usually these start with the from but that's just a convention also but I'm going to call this from string and remember that we automatically accept the class as the first argument there and I'm just going to call this second argument employee string and now we're just going to go ahead and parse this string for them so exactly what we did down here I'm just going to grab this line first name last name and pay and I'm going to go ahead and put this in our class method but now instead of working with this specific string I'm going to split the string that they pass to this method so instead of employee string one I'm going to use this employee string argument from this method here and down here at the bottom we created our new employee by saying employee and then passing in those variables that we got when we split but now that we're inside of our class method we can do the exact same thing but now we're going to use our class variable instead of employee because those are the same thing so I'm going to go ahead and grab this line here and paste it in but now I'm going to use this class instead of employee since that's basically the same thing so this line is going to create that new employee and now that we've created that new employee we also need to return it so that they can receive that employee object when this method is called so I'm just going to return that new employee object okay so now our alternative constructor is done so now I can delete this line here and now instead of someone needing to parse the string themselves we've provided them with this from string method that they can call and you see here that they are just passing in this employee string one and it comes in here and it splits that string on the - and then creates a new employee object and then returns that employee object so now if I save this and run it you can see that we got the exact same values so now they'd have no need to parse the strings anymore we've provided them with a from string alternative constructor and now they can just pass in those strings and get their new employee objects so when people say that they use class methods as alternative constructors then this is what they mean now if you want to see a real-world example of this then I have the date/time module pulled up here and there are several ways that we can create new date times and if you search for class method within the date/time module then you can see an example of some of these so the default way of creating a date/time object is to say something like date/time and then pass in the year month and date but if we look here at these class methods which are alternative constructors then what they do is they have this from time stamp and you can use the current time which is today and they have a couple of other examples here as well and you can see that they're basically doing the same thing that we just did in our example so you can see that they are accepting the class and a timestamp with this from time stamp constructor and then they are parsing out some dates and then they're creating that new date/time object and returning that so it's a new way of creating date/time objects so that is very similar to the example that we just wrote on our own so now if you ever see something like this in code then you'll know what's going on okay so now that we looked at class methods now let's talk about static methods now a lot of people gets class methods and static methods confused now when working with classes regular methods automatically pass the instance as the first argument and we call that self and class methods automatically pass the class as the first argument and we call that CLS and static methods don't pass anything automatically they don't pass the instance or the class so really they behave just like regular functions except we include them in our classes because they have some logical connection with the class so let's go ahead and take a look at an example so that we know what we mean here so I'm going to go ahead and delete these lines here so let's say that we wanted a simple function that would take in a date and return whether or not that was a workday so that has a logical connection to our employee class but it doesn't actually depend on any specific instance or class variable so instead I'm going to make this a static method so to create a static method it's just as easy as a class method and we're also going to use a decorator that decorator is going to be static method so I'm going to call this method is workday now remember static methods don't take the instance or the class as the first argument so we can just pass in the arguments that we want to work with and I'm going to take in a day here and return whether or not that is a workday so to make this a simple example I'm not going to do it to anything too complicated I'm just going to return whether or not our day falls on a weekday so in Python dates have these weekday methods where Monday is equal to zero and Sunday is equal to six and all the other days in between so if I wanted to return whether this is a weekday and I could just say they dot weekday if that is equal to five well which is a Saturday and I'm going to go ahead and just copy this line here and say or if that day is equal to six which is a Sunday then I'm going to return false and if it doesn't hit that conditional then it means that it's a weekday so I'm just going to return true now sometimes people write regular methods or class methods that actually should be static methods and usually a giveaway that a method should be a static method is if you don't access the instance or the class anywhere within the function so say that I had this class method up here you can see that I'm using that class variable there but if I wasn't using it anywhere within that method then it probably doesn't need to be a class method and the same with regular methods if you're not using that self variable then it's probably you probably want to check and see if that would be appropriate to use a static method that place okay so now let's go down here and see if our static method is working so I'm just going to go ahead and uncomment out these couple of lines here and all I'm doing here is I'm importing the eighth time module and then I'm creating a new date and if I wanted to use our new static method here that checks whether this date is a weekday then I can just print out the employee dot is work day and pass in that date so if I run that on I got an error there because whenever I copied and pasted I forgot to take out this second if I really want that to say if the weekday is equal to five or the weekday is equal to six so now if I save that and run it then you can see that this day that I passed in is false because that's actually a Sunday now if I replace this with the 11th and run that now you can see that it's a Monday so you can see that his workday returns true okay so I think that is going to do it for this video in this video we learned the difference between regular instance methods class methods which can also be used as alternative constructors and static methods which don't operate on the instance or the class so I hope all of that made sense to everyone but if you do have any questions about anything that we cover then feel free to ask in the comment section below and I'll do my best to answer those in the next tutorial we'll start looking at inheritance and how we can make subclasses now if you enjoy these tutorials and would like to support them then there are several ways you can do that the easiest way is to simply like the video and give it a thumbs up and also it's a huge help to share these videos with anyone who you think would find them useful and if you have the means then you can contribute through patreon and there's a link to that page in the description section below be sure to subscribe for future videos and thank you all for watching
Info
Channel: Corey Schafer
Views: 1,415,981
Rating: undefined out of 5
Keywords: Python, Python Tutorial, Python Classes, classmethod, staticmethod, classmethods, staticmethods, Classes, OOP, Object Oriented, Python Objects, Class Variables, Class Attributes, Class Methods, Static Methods, Python OOP, Class, Python Class, Decorators, Python Decorator, classmethod vs staticmethod, Object Oriented Programming, @classmethod, @staticmethod
Id: rq8cL2XMM5M
Channel Id: undefined
Length: 15min 20sec (920 seconds)
Published: Mon Jul 11 2016
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.