Python OOP Tutorial 4: Inheritance - Creating Subclasses

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
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
Info
Channel: Corey Schafer
Views: 820,904
Rating: 4.9872684 out of 5
Keywords: Python, Python Tutorial, Python Classes, Classes, Inheritance, Subclass, Subclasses, Python Inheritance, Python Subclass, Python Subclasses, Python Class, overriding, Python Override, Python super, super, Method Resolution Order, MRO, Python Method Resolution Order, Python MRO, OOP, Object Oriented, Object Oriented Programming
Id: RSl87lqOXDE
Channel Id: undefined
Length: 19min 40sec (1180 seconds)
Published: Mon Jul 25 2016
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.