Python OOP Tutorial 4: Inheritance – Creating Subclasses
Video Title: Python OOP Tutorial 4: Inheritance – Creating Subclasses
hey everybody how’s it going in this video we’ll be learning about Python class inheritance now just like it sounds inheritance allows us to inherit attributes and methods from a parent class now this is useful because we can create subclasses and get all the functionality of our parent class and then we can overwrite or add completely new functionality without affecting the parent class in any way so let’s go ahead and look at an example of this and we’ll see why this is useful so for our object-oriented video so far we’ve been working with this employee class now let’s say that we wanted to get a little more specific here and create different types of employees so for example let’s say that we wanted to create developers and managers now these will be good candidates for subclasses because both developers and managers are going to have names email addresses and a salary and those are all things that our employee class already has so instead of copying all this code into our developer and manager subclasses we can just reuse that code by inheriting from employee so let’s go ahead and create these developer and manager subclasses and it’s just as easy as creating a new class just like we did up here with employee but we’re going to call this new class developer and after the name of class we can put these parentheses here and specify what classes that we want to inherit from so in this place we want to inherit from the employee class now I’m just going to put in this past statement here for now because I want to show you that by simply inheriting from that employee class that we inherited all of its functionality so right now even without any code of its own the developer class will have all of the attributes and methods of our employee class so right now down here I have two instances of our employee class and then I’m printing out both of their emails so if I save this and run it you can see that when we create two new employees and print out their emails that we get this result so now instead of creating two new employees I’m now going to create two new developers and pass in all of the same information so now if I rerun this and print out those emails you can see that those two developers were created successfully and we can access the attributes that were actually set in our parent employee class so what happened here is that when we instantiated our developers it first looked in our developer class for our annette method and it’s not going to find it within our developer class because it’s currently empty so what python is going to do then is walk up this chain of inheritance until it finds what it’s looking for now this chain is called the method resolution order now I want to show you there’s really useful function here that makes these things a lot easier to visualize and that is the help function so first I’m going to copy out these two lines here and then I’m just going to print out this help function and I’m going to pass in the developer class so if I go ahead and run that and I’m going to make this a little bit bigger here now you can see that when we run help on that developer class that we get all kinds of good information here so that method resolution order that I mentioned is one of the first things that gets printed out and basically these are the places that Python searches for attributes and methods so when we created our two new developers here it first looked at our developer class for the init method and when it didn’t find it there then it went up to the employee class and it found it there so that’s where it was executed now if it hadn’t found it in our employee class then the last place that it would have looked is this object class and every class and Python inherits from this base object now if we look at this output further then it actually shows the methods that were inherited from employee so you can see here that we have the net method and we also have our apply raised method and our full-name method and if I keep scrolling down here then you can also see that we have our data and other attributes and you can see that the class attribute raised amount was also inherited from the employee class so we got all of this code for free just by inheriting from that employee class okay so now I’m going to go ahead and make this smaller again and I’m going to take out that printed help statement okay so now let’s say that we wanted to customize our subclass a little bit now I’m going to make a simple one-line change in here and I’m just going to change the raise amount but first let’s go ahead and see what happens when we apply arrays on our current developer so I’m going to print out this should actually be pay and this should be pay now I’m going to print out our current developers pay here which should be 50,000 then I’m going to apply a raise and it should find our employees raise amount of 4% and that I’m going to reprint out that developers pay again so if I save that and run it you can see that it printed out 50,000 applied the raise and then printed out 4% higher but let’s say that we wanted our developers to have a raise amount of 10% now to change that it’s just as easy as coming into our developer class here and it’s changing the raise amount to 10% so now if I go ahead and rerun this you can see that it used our developer class’s raise them out instead of our employee classes raise them out now if I was to change this instance back to an employee instead of a developer and then reran this then you can see that now it’s back to that employee 4% amount so the thing to take away here is that by changing the raise amount and our subclass it didn’t have any effect on any of our employee instances so they still have that raise amount of 4% so we can make these changes to our subclasses without worrying about breaking anything in the parent class okay so now I’m going to go ahead and change this back to a developer and we’ll make a few more more complicated changes so sometimes we want to initiate our subclasses with more information than our parent class can handle so what do I mean by that so let’s say that when we created our developers here that we wanted to also pass in their main programming language as an attribute but currently our employee class only accepts first-name lastname and pay so if we also wanted to pass in a programming language there then to get around this we’re going to have to give the developer class its own and net method so what I’m going to do is I’m just going to go up here to our employee class and grab that init method and I’m going to paste it here within the developer class now along with the first name last name and pay I’m also going to add in an argument here for the programming language now what you might be tempted to do here is just go up and copy all of this code from our employees classes and knit method and paste it into our developer classes init method but we don’t want to do that because we want to keep our code dry and not repeat this logic in multiple places because we want it to be as maintainable as possible so instead of copying and pasted pasting that what we’re instead going to do is just let our employees and knit method handle the first name last name and pay and then we’ll let the developer set the programming language so in order to let that employee handle the first name last name and pay what we can do here is just do super dot and knit and then we can pass in the first last and pay so again super dot knit is going to pass first last and pay to our employees and knit method and let that class handle those arguments now there’s multiple ways of doing this logic here you may have seen some people do employee dot a knit and instead of passing in first last and pay they’ll type in self and then first last and pay now both of these ways of calling the parents and knit method will work but I tend to use super because with single inheritance like we are using here it’s a little bit more maintainable but it’s really necessary once you start using multiple inheritance and we’re going to go over that in a future video but to keep things simple I usually just like to always stick with super so now that we’re letting our employee classes a tenth method handle the first last and pay now we can handle the programming language argument just like we would in the other class so I can just say self dot programming language equals the programming language that we passed in here okay and that should be all we need for our anit method so now when we instantiate our developers down here it’s also going to be expecting a programming language to be passed in so I’m just going to go ahead and pass in Python for our first developer and I’ll pass in Java for our second developer so now to make sure that this worked I’m going to comment out those lines there and I’m going to print out the first developers email I’m also going to print out the first developers programming language okay so if I run that then you can see that both of those were set correctly so we got the email set I it when we passed in all of our arguments here it came up here and it ran our employees and knit method and set all of those within there and then it also set our programming language within our developers init method there so you can see why this sub classing is useful because we were able to customize just a little bit of code and we got all of this code from our employee class for free just by adding in that one little line there okay so just so we can get a really good understanding of this let’s go through the process of creating another subclass called manager and I’ll go through all these steps again but I’ll go a little bit faster this time okay so right here below our developer I’m going to create a another class and I’m going to call this class manager and if this is also going to inherit from employee now when I create a new manager I’m going to give the option of passing in a list of employees that this manager supervises so we’re going to need to add an a knit method for our manager and instead of typing all this in I’m just going to grab this Anette method here from our developer and paste this in here okay but this is going to be a little bit different instead of a programming language for our manager I’m going to let them pass in a list of employees and I’m going to set the default to none and then instead of setting this programming language here I’m say if employees is none self dot employees is equal to an empty list and then else self dot employees equals employees now you might be wondering why I didn’t just pass in an empty list as default argument here instead of none but you never want to pass mutable data types like a list or a dictionary as default arguments and that’s a topic for another video and I plan on doing one on that soon but for now we’ll just go ahead and set our employees to an empty list if the argument is not provided and set them equal to that employees list if it is okay so now let’s add in a few methods here so I’m going to give the option to add and remove from our list of employees that our manager supervises and to do this I’ll add in a method called add employee and add employee will take self just like all of our instance methods do and employee and then I’ll just say if the employee is not in self dot employees then I will just append that employee to our lists so self dot employees dot append that employee and now I’m also going to create another method here to remove employees from this list and it’s going to be similar so I’m just going to go ahead and copy that but this is going to be removed and we’ll say if the employee is in our list of employees then remove that employee ok and lastly I’m going to add a method that will print out all of the employees that this manager supervises so I’m going to call this method print employees and this isn’t going to take any more arguments than just self and I’ll say for employee in self dot employees and then I will just print out that employee and before the employee I’ll go ahead and put an arrow here just so it sticks out a little bit further and instead of just printing the employee I’ll actually print the employee full-name okay so I think that we are finished with our manager class so we have our own init method here which it’ll accept a first name last name and pay and also a list of employees that this manager supervises and then we have the ability to add employees to that list remove employees from that list and to print out all the employees from that list so now let’s see if this works so I’m just going to comment out these lines here and now I’m going to create a new manager and I’ll call this manager one so now I want this to be a manager and for the first name I’ll do su for the last name I’ll do Smith will say that the pay is ninety thousand and let’s say that she supervises this first developer here so now let’s make sure that this manager was successfully created and that we have all of the attributes and methods available that it would have inherited from that employee class so let’s go ahead and print out this managers email address so now if I go ahead and print this out you can see that the email address was set correctly but now we also added down all of this extra functionality so let’s see if we can print out all the employees that this manager supervises so I’ll do manager dot print employees and if I go ahead and run that then you can see that it prints out the full name of the one employee that they currently supervise and I can add to that list of employees so here I’ll just say manager one dot employee and I’ll pass in this second developer here before we print out that list of employees now if I print that out you can see that now they are supervising two employees and we also have the ability to remove employees so I will remove our first employee here from their list of people who they supervise so now if I save that and run it you can see that that first developer was removed from that list and they only have the second developer in that list so just like with our devel upper-class you can see how useful this actually is because all of the code in here is specific to what we want for a manager and in our developer class it’s specific to what we want for a developer and we’re inheriting all of this common code from employee so we really get to reuse our code nicely here if we use subclass incorrectly okay so now I’m just going to go ahead and remove all of this code here now I know that this video is getting a little long but I want to show you a couple more quick things here so python has these two built-in functions called is instance and is subclass so is instance will tell us if an object is an instance of a class so for example if I need to print this out I can print out whether manager one is an instance of manager and if I print that out you can see that it prints true now if I was to check whether the manager is an instance of an employee then you can see that that is also true but if I check if manager one is an instance of a developer then that returns false because even though developer and manager both inherit from employee they aren’t part of each other’s inheritance so along those same lines we have this is subclass function and is subclass will tell us if a class is a subclass of another so for example I could do is developer a subclass of employee and if I run that you can see that it returns true and if I do is manager a subclass of employee if I run that you can see that that returns true also but if I say is manager a subclass of developer then that will return false so those built in is instance and is subclass functions may come and use when you’re experimenting with inheritance on your own ok so very last thing I always like to show you all practical real-world examples of this stuff whenever I can and one of the easier examples I found up sub-classing was within the exceptions module of this Python whisky library so this is a really popular library and used in a lot of different projects so if we look here we can see that this HTTP exception class inherits from this base exception and they say here that this HTTP HTTP exception is the base class for all HTTP exceptions now if we scroll down here you can see this is that this has a lot of code in this class but once we get far enough along we can see that we have some other classes here that inherit from that base HTTP exception class so here we have this bad request that inherits from HTTP exception and since it inherits from that base class it gets all of that code that we just solve for free and now it can just simply modify this return code and a description without needing to rewrite all of that code from the parent class so you can see how using inheritance like this would be extremely useful as your projects grow in size and makes everything much easier to maintain okay so I think that is going to do it for this video in the next video we will go over special and magic methods and how to use those within classes but if you do have any questions about what we covered in this video then feel free to ask in the comment section below and I’ll do my best to answer those 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 you can contribute through patreon and there’s a link to that page in a 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
Great job Corey. You have explained the topic very well!
At 11:30, can the list of employees just be a list of strings for employee names, or should it be a list of employee objects.
I know later he uses emp.fullname() later so they are employee objects but i was just wondering if they have to be employee objects.
Can someone tell me which IDE Corey is using?
If you have OCD, __init__() and super().__init__() buggs the hell out of you 🙂
Liked the real world example at the end! Great video!
Thanks Corey
the best example and explanation of how to extend a sub-class's parameters that I have come across on the web.
keep up the good work!
I finally get it, thank you!
Amazing tutorial, helped me a lot. Thank you!
did @corey explain why we shouldnt do that in @11:24
great vids and content, Corey!
I am 65 yrs old, disabled, living month to month off the SSA. I have an old old HP that I bought refurbished from Amazon. I've installed Python and Pycharm. I also use the computer to watch Corey Schafer on YouTube. With each video I learn a little more about Python and computer science in general. Many videos I have to watch several times. So far Iv'e coded a really nice Mandelbrot Imager (see my account photo), a working gravity simulator, a script that codes the RGB values for over 200 colors that I call Crayons.py and a bunch of quick calculator functions for algebra, and calculus. All of which gave me great joy and pride of accompliment. Thank you Mr Schafer for bringing a little warmth to my life.
Thanks a lot, great explanantion
I must say, I have TCM security subscription for python 201 which has a similar lecture on "Inheritance". TBH Corey provided more key points
Thank you!
Thank you
thank you so helpful!
12:55
I havent taken my comp sci class in about a year and its really nice to relearn the materials through these videos, thanks for all the help.
This is a benchmark for teaching, period.
Thank you for creating this video for us. I have a question. I noticed that you didn’t add “self.” in method “add_emp”. Shouldn’t it be “self.emp”?
q
Around 13:25, ive poured over my code, and it seems to be the same as yours, but when I run the print_emps code, i get, 'str' object has no attribute 'fullname', the add and remove lines show <in string> requires left operand, not Developer. Im not sure where I went wrong, as Ive rewatched this video several times, although still very new to python.
Can you do a video about multiple inheritance with super()? Or if you already did one, can you put a link to it please?
thank you so much for this video! I have been struggling through my Python Class; you are a God send!
Corey Schafer sir, you are awesome. You just explained all these advanced concepts so easily. Moreover you really showed us the real time application of these code. I myself used all these in Django while handling custom error messages. Thanks a lot for making and explaining us these amazing concepts. Hats off to you sir ❤
General question: ~ at 12:19 Corey is using "employees" as parameter name in _init_ but uses "emps" as abbreviation when naming the method "add_emp" and uses "emp" for the employee-parameter. Is there some kind of general convention when to use abbreviations and when not to use them or is this more a "personal style thing"?
Sensei, your instruction technique is superior to all others.
The content Corey creates is a gold mine !!! How well he explains the concepts. Whoever follow Corey's lectures are doomed to have rock solid understanding of the technical concepts. #CoolCorey