Python OOP Tutorial 3: classmethods and staticmethods
![*](https://i0.wp.com/allprowebdesigns.com/wp-content/uploads/2024/04/1712975288_maxresdefault.jpg?resize=840%2C430&ssl=1)
Video Title: Python OOP Tutorial 3: classmethods and staticmethods
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
-
Sale!
Wireless WIFI Repeater Extender Amplifier Booster 300Mbps
$29.99$14.99 Add to cartWireless WIFI Repeater Extender Amplifier Booster 300Mbps
Categories: Electronics, Wi-Fi Router, Wireless Wi-Fi Extender Tags: 300Mbps, 802.11N, Amplifier, Booster, Extender, mobile wi-fi booster, Remote, WIFI, Wireless, Wireless WIFI, Wireless WIFI Repeater, Wireless WIFI Repeater Extender, Wireless WIFI Repeater Extender Amplifier, Wireless WIFI Repeater Extender Amplifier Booster, Wireless WIFI Repeater Extender Amplifier Booster 300Mbps$29.99$14.99 -
Sale!
Full RGB Light Design Gaming Headset Headphones with Mic
$24.99$14.99 Add to cartFull RGB Light Design Gaming Headset Headphones with Mic
Categories: Electronics, Gaming, Gaming Headsets Tags: Design, Full, Full RGB Light Design Gaming Headset, Full RGB Light Design Gaming Headset Headphones, Full RGB Light Design Gaming Headset Headphones with Mic, Gamer, Gaming, Gaming Headset Headphones, gaming headset wireless, Headphone, Headphones, Headset, Light, Mic, Package, RGB$24.99$14.99 -
Sale!
Wireless BlueTooth Multi-Device Keyboard Mouse Combo
$39.99$19.99 Add to cartWireless BlueTooth Multi-Device Keyboard Mouse Combo
Categories: Electronics, Gaming, Gaming Keyboards, Keyboard Mouse Combos Tags: Combo, Keyboard, keyboard mouse combos, Mouse, MultiDevice, Set, WireKeyboard Mouse Combo, Wireless, Wireless BlueTooth Keyboard Mouse Combo, Wireless BlueTooth Keyboard Mouse Combos, Wireless BlueTooth Multi-Device Keyboard Mouse Combo, Wireless BlueTooth Multi-Device Keyboard Mouse Combos$39.99$19.99 -
Sale!
High Back Leather Executive Adjustable Swivel Gaming Chair with Headrest and Lumbar
$199.99$139.99 Add to cartHigh Back Leather Executive Adjustable Swivel Gaming Chair with Headrest and Lumbar
Categories: Gaming, Gaming Chairs Tags: Adjustable, Chair, computer chairs, Desk, Executive, Gaming, Girl, Headrest, High, High Back Leather Executive Adjustable Swivel Gaming Chair, High Back Leather Executive Adjustable Swivel Gaming Chair with Headrest, High Back Leather Executive Adjustable Swivel Gaming Chair with Headrest and Lumbar, High Back Leather Executive Adjustable Swivel Gaming Chairs, Leather, Lumbar, Office, Racing, Swivel$199.99$139.99 -
Sale!
Professional LED Light Wired Gaming Headphones with Noise Cancelling Microphone
$29.99$19.99 Select optionsProfessional LED Light Wired Gaming Headphones with Noise Cancelling Microphone
SKU: N/A Categories: Electronics, Gaming, Gaming Headsets Tags: Cancelling, Gaming, Gaming Headphones with Noise Cancelling Microphone, gaming headset, Headphones, Headset, LED, Light, Mic, Microphone, Noise, Professional, Professional LED Light Wired Gaming Headphones, Professional LED Light Wired Gaming Headphones with Noise Cancelling Microphone, Wired, Wired Gaming Headphones, Wired Gaming Headphones with Noise Cancelling Microphone$29.99$19.99 -
Sale!
Gaming Desk with LED Lights USB Power Outlets and Charging Ports
$349.99$249.99 Select optionsGaming Desk with LED Lights USB Power Outlets and Charging Ports
SKU: N/A Categories: Computer Desk, Gaming, Gaming Desk Tags: and Charging Ports, Charging, Desk, Desks, Gaming, gaming desk with led lights, Gaming Desks with LED Lights, Home, LED, Lights, Monitor, Office, Outlets, Port, Power, Room, Stand, USB, USB Power Outlets, White, Workstation$349.99$249.99 -
Sale!
Wired Mixed Backlit Anti-Ghosting Gaming Keyboard
$99.99$79.99 Add to cartWired Mixed Backlit Anti-Ghosting Gaming Keyboard
Categories: Electronics, Gaming, Gaming Keyboards Tags: Antighosting, Backlit, Blue, brown, Gaming, Gaming Keyboard, gaming keyboards, gaming keyboards and mouse, Keyboard, Laptop, Switch, Wired, Wired Mixed Backlit Anti-Ghosting Gaming Keyboard, Wired Mixed Backlit Anti-Ghosting Gaming Keyboards, Wired Mixed Backlit Gaming Keyboard$99.99$79.99 -
Sale!
Wireless Bluetooth 5.3 ANC Noise Cancellation Hi-Res Over the Ear Headphones Headset
$119.99$59.99 Add to cartWireless Bluetooth 5.3 ANC Noise Cancellation Hi-Res Over the Ear Headphones Headset
Categories: Electronics, Gaming, Gaming Headsets Tags: 5.3 ANC Noise Cancellation Hi-Res Over the Ear Headphones Headset, ANC, Audio, Bluetooth, Cancellation, Ear, Earphone, gaming headset, Headphones, Headset, Hi-Res Over the Ear Headphones Headset, HiRes, Noise, Wireless, Wireless Bluetooth 5.3 ANC Noise Cancellation Hi-Res Headphones, Wireless Bluetooth 5.3 ANC Noise Cancellation Hi-Res Over the Ear Headphones Headset, Wireless Bluetooth 5.3 ANC Noise Cancellation Hi-Res Over the Ear Headphones Headsets$119.99$59.99 -
Sale!
Wired Sports Gaming Headset Earbuds with Microphone
$19.99$9.99 Select optionsWired Sports Gaming Headset Earbuds with Microphone
SKU: N/A Categories: Gaming, Gaming Headsets Tags: Accessories, Earbud, Earphone, Earphones, Gaming, gaming headset with microphone, Headphones, Headset, IOS, Microphone, Sports, Wired, Wired Sports Gaming Headset Earbuds, Wired Sports Gaming Headset Earbuds with Microphone, Wired Sports Headset Earbuds$19.99$9.99 -
Sale!
150W Universal Multi USB Fast Charger 16 Port MAX Charging Station
$49.99$29.99 Add to cart150W Universal Multi USB Fast Charger 16 Port MAX Charging Station
Categories: Charging Stations, Electronics Tags: 150W, 150W Charging Station, 150W Universal Multi USB Charging Station, 150W Universal Multi USB Fast Charger 16 Port MAX Charging Station, 150W Universal Multi USB Fast Charger 16 Port MAX Charging Stations, 150W Universal Multi USB MAX Charging Station, 16 Port MAX Charging Station, 3.5A, Charger, Charging, Fast, laptop charging stations, Max, Multi, Port, Stand, Station, Universal, USB$49.99$29.99
Corey Schafer tutorial is great. How to call classmethod fromtimestamp? I tried, but I got an error. Thank you in advance.
You need to have this course on Coursera. You need to make money from this excellence
Corey The Schauffer ,, great
In the alternative constructor you returned the class object 'cls(first,last,pay)' how will this lead to creation of new employee since at the class defintion definition there is no provisioin to pass arguments?
what is "weekday" from that and how did you assign the value?
Why are you not charging for it?
By the way thanks.
Are you a university professor?
So basically Static Methods are like normal functions that work within a class but without using the instance of the class….
What's the disadvantage of using a class method decorator when it should rather be a static method? it won't throw an error nor change the output (at least in this example, when we change static method to class method and just make sure to include cls as an argument). is it just a convention (eg. for clarity for future readers) or will it cause some problems down the line?
please upload furtther videos
Thanks 🙂
That's the content i pay my internet bill for awesome job❤
still watching your videos in 2024. Fantastic teacher!
Amazing vid once again
Thank you😍
Awesome!, finally understood after several videos
The variables under cls method are instantance or class variables?
I really appreciate you mentioning the common mistakes that people usually make
Great tutorials, even without an in-depth knowledge of the language I was able to follow and replicate the work
Hey,
For some reason my methods are not passing class automatically and I get the error of needing 2 additional argument. Now, if I add Employee as an argument along with the amount it works. Any idea what’s going on?
Thank you.
dude, this is like the best tutorial out there. I've been trying to understand class methods, and I've just been confused at how other people have taught it, but Corey Schafer's beginner friendly way of teaching and his way of just explaining all the little things just helped me clear out a lot of the rubble for me.
Quick question. How come when I do the “set raise amount “ method I get an error saying I’m missing 1 required function unless I type in Employee as the first? I have everything exactly as you have it, so what’s going on? Do some IDE’s not accept it automatically? I hate to ask questions s I understand this is more of a “see and do” type of thing as it’s laid out perfectly, but it’s driving me nuts. Thank you for any response.
does cls.raise_amt point to the same as the class variable raise_amt on the top of the class?
Thank you
Why do we need the decorator @classmethod? Can't we just define the function without put the decorator beforehand?
When you use Apply_raise function on emp1 why they also change the raise_amt of emp2?
Thanks corey, my concepts are quite clear after watching your python videos.
Great Teacher Corey.
Pending a subjectively I'd request the information as interrogative question at first.. undergoing the complete understanding is the location request is relative from beyond the X4
q
why did you use .weekday() inside your method.. in that way you should always pass datatime instance to your static method otherwise it doesn't have .weekday() method in it?
if you had any reason for doing that plz make me understand
Great video! I've been slowly learning Python and this content is very helpful. However, a minor point that whenever I see a method like is_workday() that has, "if condition: return True; return False", I always try to refactor into: "return(condition)" which is usually much more concise while still being readable. For instance:
def is _workday(day):
return(day.weekday() <= 4)
or,
def is_workday(day):
return(day.weekday() in range(5))
perfect
helped me tame a bunch of code that was getting out of control by writing a simple class, including a mix of instance methods and static methods
thanks to your explanations, way easier than it might have been
many thanks for sharing your knowledge
Thank you for the videos
You are a genius teacher, sir. The timedate constructor is exactly what I was trying to achieve in a timezones processor script that accepts different input, from current timestamp or from a string argument, but I wasn't satisfied until now (now I know what to use instead)
The best python teacher 🙌
I really enjoy your videos, they're very educational! (and @10:15 – line 709, revealed a hidden gem of a pick-up line: 'hey you, would you like to construct a date from a proleptic Gregorian ordinal?')
DAMNNNN YOU ARE THE BEST 4 REAL
sir do you have video on private, public method video with use case
Thanks for the amazing tutorial! Does it still work without the @staticmethod decorator?
Thanks a tons.