Python OOP Tutorial 2: Class Variables
Key Takeaways
The video tutorial covers Python Object-Oriented Programming, focusing on class variables, their usage, and differences from instance variables, with examples and code demonstrations.
Full Transcript
hey there how's it going everybody in the last video we learned how to create a simple class and how to create instances of that class we learned a lot about instance variables which are used for data that is unique to each instance so instance variables are these here that are set using the self argument that we saw before so for example in the employee class that we created we set the names the email and the pay in our Annette method and those are set for each instance of the employee that we create and I briefly mentioned class variables in the last video but we didn't go into detail and that's what we're going to learn about in this video so class variables are variables that are shared among all instances of a class so while instance variables can be unique for each instance like our names and email and pay class variables should be the same for each instance so if you look here at our employee class what kind of data would we want to be shared among all employees well there's a lot of different ideas that we could probably come up with but for this example let's say that our company gives annual raises every year now the amount can change from year to year but whatever that amount is it's going to be the same for all employees so that would be a good candidate for a class variable now before we actually create that class variable let's first hard code this in and see why the class variables would be a better use case so I'm going to create a method down here called apply raise and remember our methods automatically take in the instance which we are going to call self now within this apply raise I'm going to do a self dot pay and I'm going to set this equal to an integer so that we have a whole number and I'm gonna do self dot pay times 1 point let's just make this 4% so now if I was to test this down here on an instance then I can print out the employee 1 dot pay and let me go ahead and copy this twice and between here I'm going to do an employee 1 dot apply raise now if I go ahead and run this Oh actually forgot to put in the parenthesis there so now if I go ahead and run this you can see that I printed out the pay then we applied the raise and it added 4% onto our pay so we can see that it worked but there are a couple of things wrong here so first it would be nice if we could access the raise amount by doing something like employee 1 dot raise amount or since it would apply to the entire class we should also be able to get the raise amount by doing employee dot raise amount now that raise amount attribute doesn't currently exist so we can't see that it is 4% and also what if I wanted to easily update that 4% amount so right now it's kind of hidden within this method and for all I know it could be in multiple places throughout our code so we don't want to have to manually go in if we wanted to update this 4% we wouldn't want to have to manually go in and change these and multiple locations so let's instead pull this 4% out into a class variable and that's as easy as going up here to the top of the class and just saying that we want a raise amount equal to one point and we'll just do that at 4% still so now instead of hard-coding this 4% down here and our apply raise method now let's go ahead and use this class variable now you might expect us to just be able to type in raise amount here but if I save that and I'm going to comment out these lines here so if I save that and run it you can see that I got a name error and it says that raise amount is not defined and that's because when we access these class variables we need to either access them through the class itself or an instance of the class so within the apply raise I could either say employee not raise amount and if I save that and run it then you can see that that works or I can also access through the instance so I can do self dot raise amount and if I run that then you can see that that works as well now that might be a little confusing to you because if these are class variables and why can we access them from our instance so let me print out a few lines here to get a better idea of what's going on so I'm going to go ahead and remove all of these lines here actually I'm going to keep this and I'm going to print out the employee one dot rays amount and I'm also going to print the employee that rays amount and also just to see all of our instances here I'm going to also do the employee two trays amount so that we can see all of them together so now if I go ahead and print these out you can see that I can access this class variable from both my class itself as well as from both instances now what's going on here is that when we try to access an attribute on an instance it will first check if the instance contains that attribute and if it doesn't then it will see if the class or any class that it inherits from contains that attribute so when we access rays amount from our instances here they don't actually have that attribute themselves they're accessing the class's raiseamount attribute now there's a little trick that we can do here to get a better idea of what's going on so I'm going to go ahead and print out the namespace of employee one and we can do that by printing out employee one double underscore vicked it's now if I run this if I were to access these names or email or pay then these are the values that they would return but you can see that there's no raise amount here in this list now if I print it out the employee dict and run that now we're gonna get a few things here that we don't necessarily care about but if we look down here and we can see that the class does contain this raise amount attribute and that is the value that our instances see when we access that raise amount attribute from our instances now let me show you an important concept here so I'm going to go ahead and comment this out and I'm going to take this employee raise them out and I'm going to set this equal to one point zero five and now I'm going to uncomment out our print statements here and rerun this code and you can see that it changed the Rays amount for the class and all of the instances now what if I was to set the Rays amount using an instance instead of using the class so instead of doing employee dot rays amount equals five percent I'm going to say employee one dot rays amount equals five percent so if I run this now now this might be a little unexpected you can see that it only changed the Rays amount for employee one it's the only one that has this five percent so why did it do that well when we made this assignment it actually created the Rays amount attribute within employee one so if I go back up here and print back out employee ones namespace and I'm going to do this under the assignment so now if I run that now you can see that employee one has raised amount within its name space equal to five percent and it finds this within its own namespace and returns that value before going and searching the class and we didn't set that raise amount on employee two so that still falls back to the classes value now that's an important concept to understand because up here and our apply rays method we can see that we could get different results depending on whether we did the self which is the instance raised amount or the employee class raise amount so in this case I think I'm going to go ahead and leave this as self dot raise amount because that will give us the ability to change that amount for a single instance if we really wanted to so if I wanted to change employee ones raise amount then I could go ahead and do that and when I did apply raise then it would use the employee ones raise amount instead of the classes raise amount and also using self here will allow any subclass to override that constant if they wanted to and we'll look at sub classing and future video so now let's look at another example of a class variable where it wouldn't really make sense to use self so let's say that we wanted to keep track of how many employees that we have so the number of employees should be the same for all instances of our class so if I created a class variable up here I'm just gonna go ahead and call this num of employees is equal to zero for now and each time we create a new employee I'm going to increment that by one and I can do that within the knit method since the knit method runs every time we create a new employee so within here I'm going to do employee dot number of employees plus equals one now I'm definitely gonna use employee that number of employees here instead of self dot number of employees because with the raises it's nice to have that constant class value that can be overridden per instance if we really need it to be but in this case there's no use case I can think of where we would want our total number of employees to be different for any one instance so for now I'm going to go down here to the bottom and go ahead and delete all of this and I'm going to print out employee dot number of employees so now if I go ahead and run that you can see that it returned two because it was incremented twice when we instantiated both of our employees here if I was to put this print statement above where we instantiated those employees then you can see that it was zero and we created two employees and then it printed out - okay so I think that is going to do it for this video now I know that that was a lot to take in but hopefully now you better understand the difference between instance variables and class variables and when you would use each one so one of the obvious next questions is well if we have class variables then are there also class methods and the answer is yes there are these things called static methods and also class methods and we'll look at the difference between those in the next video but if you do have any questions about what we covered here then feel free to ask and section below and I'll do my best to answer those 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 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 class variables. We will see how they differ from instance variables and also some ideas for exactly how we would want to use them. 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