Python OOP Tutorial 3: classmethods and staticmethods
Key Takeaways
This video tutorial by Corey Schafer covers class methods and static methods in Python, including their usage, benefits, and examples, utilizing tools such as Python and the datetime module.
Full Transcript
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
Original Description
In this Python Object-Oriented Tutorial, we will be learning about classmethods and staticmethods. Class methods are methods that automatically take the class as the first argument. Class methods can also be used as alternative constructors. Static methods do not take the instance or the class as the first argument. They behave just like normal functions, yet they should have some logical connection to our class. We will look at some examples of both of these in order to understand both in depth. Let's get started.
Python OOP 1 - Classes and Instances - https://youtu.be/ZDa-Z5JzLYM
Python OOP 2 - Class Variables - https://youtu.be/BJ-VvGyQxho
Python OOP 3 - Classmethods and Staticmethods - https://youtu.be/rq8cL2XMM5M
Python OOP 4 - Inheritance - https://youtu.be/RSl87lqOXDE
Python OOP 5 - Special (Magic/Dunder) Methods - https://youtu.be/3ohzBxoFHAY
Python OOP 6 - Property Decorators - https://youtu.be/jCzT9XFZ5bw
The code from this video can be found at:
https://github.com/CoreyMSchafer/code_snippets/tree/master/Object-Oriented
✅ Support My Channel Through Patreon:
https://www.patreon.com/coreyms
✅ Become a Channel Member:
https://www.youtube.com/channel/UCCezIgC97PvUuR4_gbFUs5g/join
✅ One-Time Contribution Through PayPal:
https://goo.gl/649HFY
✅ Cryptocurrency Donations:
Bitcoin Wallet - 3MPH8oY2EAgbLVy7RBMinwcBntggi7qeG3
Ethereum Wallet - 0x151649418616068fB46C3598083817101d3bCD33
Litecoin Wallet - MPvEBY5fxGkmPQgocfJbxP6EmTo5UUXMot
✅ Corey's Public Amazon Wishlist
http://a.co/inIyro1
✅ Equipment I Use and Books I Recommend:
https://www.amazon.com/shop/coreyschafer
▶️ You Can Find Me On:
My Website - http://coreyms.com/
My Second Channel - https://www.youtube.com/c/coreymschafer
Facebook - https://www.facebook.com/CoreyMSchafer
Twitter - https://twitter.com/CoreyMSchafer
Instagram - https://www.instagram.com/coreymschafer/
#Python
Watch on YouTube ↗
(saves to browser)
Sign in to unlock AI tutor explanation · ⚡30
Playlist
Uploads from Corey Schafer · Corey Schafer · 0 of 60
← Previous
Next →
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
Web fonts using CSS Font Face
Corey Schafer
Using Font Awesome in Desktop Applications (OS X)
Corey Schafer
Sublime Text 2: Setup, Package Control, and Settings
Corey Schafer
ArcGIS API for JavaScript Part 1: Our First Web Map
Corey Schafer
Mac Tip: Windows' Snapping Feature on Mac with HyperDock
Corey Schafer
Linux/Mac Terminal Tutorial: Creating Aliases for Commands
Corey Schafer
ArcGIS API for JavaScript Part 2: Starting Templates
Corey Schafer
Paver Patio Time Lapse
Corey Schafer
Mac Tip: Ways to perform Screen Capturing and Screenshots
Corey Schafer
WordPress Plugins: Imsanity
Corey Schafer
WordPress Tips: Test your theme with Theme Unit Test and Monster Widget
Corey Schafer
Sublime Text 3: Setup, Package Control, and Settings
Corey Schafer
Understanding Binary, Hexadecimal, Decimal (Base-10), and more
Corey Schafer
Mac Tip: Adding Folder Stacks to the Dock
Corey Schafer
CSS Tips and Tricks: Add External URLs to Print Stylesheets
Corey Schafer
JavaScript Arrays: Properties, Methods, and Manipulation (Part 7 of 7)
Corey Schafer
JavaScript Arrays: Properties, Methods, and Manipulation (Part 1 of 7)
Corey Schafer
JavaScript Arrays: Properties, Methods, and Manipulation (Part 5 of 7)
Corey Schafer
JavaScript Arrays: Properties, Methods, and Manipulation (Part 4 of 7)
Corey Schafer
JavaScript Arrays: Properties, Methods, and Manipulation (Part 3 of 7)
Corey Schafer
JavaScript Arrays: Properties, Methods, and Manipulation (Part 2 of 7)
Corey Schafer
JavaScript Arrays: Properties, Methods, and Manipulation (Part 6 of 7)
Corey Schafer
Python Tutorial: if __name__ == '__main__'
Corey Schafer
Sublime Text Quick Tip: "Go To Definition" Click Shortcut
Corey Schafer
How to quickly create favicons for the desktop, Apple/Android devices, tablets, and more
Corey Schafer
Easily Resize Multiple Images Using Picasa
Corey Schafer
Easily Resize Multiple Images Using the Mac Terminal
Corey Schafer
Python Tutorial: virtualenv and why you should use virtual environments
Corey Schafer
Python Tutorial: pip - An in-depth look at the package management system
Corey Schafer
Git Tutorial: Using the Stash Command
Corey Schafer
How Software Engineers, Developers, and Designers can volunteer their skills
Corey Schafer
Git Tutorial: Diff and Merge Tools
Corey Schafer
Git Tutorial: Change DiffMerge Font-Size on Mac OSX
Corey Schafer
Sublime Text Quick Tip: Launch Sublime Text from the Terminal
Corey Schafer
Python Tutorial: str() vs repr()
Corey Schafer
Programming Terms: DRY (Don't Repeat Yourself)
Corey Schafer
Programming Terms: String Interpolation
Corey Schafer
Programming Terms: Idempotence
Corey Schafer
Python Tutorial: Namedtuple - When and why should you use namedtuples?
Corey Schafer
Programming Terms: Mutable vs Immutable
Corey Schafer
Python Tutorial: Else Clauses on Loops
Corey Schafer
Overview of Online Learning Resources
Corey Schafer
Mac OS X Terminal Tutorial: Time-Saving Keyboard Shortcuts
Corey Schafer
Git Tutorial for Beginners: Command-Line Fundamentals
Corey Schafer
Quickest and Easiest Way to Run a Local Web-Server
Corey Schafer
Python Tutorial: Generators - How to use them and the benefits you receive
Corey Schafer
Python Tutorial: Comprehensions - How they work and why you should be using them
Corey Schafer
Chrome Quick Tip: Quickly Bookmark Open Tabs for Later Viewing
Corey Schafer
Programming Terms: Combinations and Permutations
Corey Schafer
Git Tutorial: Difference between "add -A", "add -u", "add .", and "add *"
Corey Schafer
Preparing for a Python Interview: 10 Things You Should Know
Corey Schafer
SQL Tutorial for Beginners 1: Installing PostgreSQL and Creating Your First Database
Corey Schafer
SQL Tutorial for Beginners 2: Creating Your First Table
Corey Schafer
SQL Tutorial for Beginners 3: INSERT - Adding Records to Your Database
Corey Schafer
Linux/Mac Terminal Tutorial: Navigating your Filesystem
Corey Schafer
Python: Ex Machina Easter Egg - Hidden Message within the Code
Corey Schafer
Mac Tip: New Split Screen Feature in El Capitan
Corey Schafer
Setting up a Python Development Environment in Eclipse
Corey Schafer
Git Tutorial: Fixing Common Mistakes and Undoing Bad Commits
Corey Schafer
SQL Tutorial for Beginners 4: SELECT - Retrieving Records from Your Database
Corey Schafer
More on: LLM Foundations
View skill →
🎓
Tutor Explanation
DeepCamp AI