5 Useful Dunder Methods In Python

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
this video was brought to you by IND dentle IO learning python Made Simple how's it going everyone in today's video we're going to be exploring five of my favorite Dunder methods which I find very useful in Python so to get started I'm going to be creating this class called fruit which takes an initializer and inside the initializer I used an asterisk to force the user to pass in both names and GRS as keyword arguments to be extra explicit then I assigned both of those values to the instance itself so there we have a basic initializer which we will be using for all of the examples and next I'm going to create a few instances of this object so as always I'm going to create my if name is equal to Main Check and my main entry point and inside here I'm going to create a few instances of this fruit and for each fruit I gave them the Alias of fub1 FS2 and F3 so the first fruit will be an apple which weighs 100 G the second will be an orange which weighs 150 g and the third will be an apple which weighs 100 G again anyway you might be asking what do I want to do with these fruits well the very first thing I want to do with these fruits is compare them I want to check if fub1 is equal to FS2 and after that I want to check if fub1 is equal to fs3 now if we were to run this you probably already know we're going to get faults back for both because the default implementation of the comparison operator for classes compares the memory addresses of the classes not their actual values so even if fub1 and F3 have the exact same values it's going to return false so what we're going to do next is Define the equality Dunder method which allows us to choose what part of the class we want to compare to another class so that we can consider them equal so let's go back to our class and Implement that functionality and I know a lot of you are going to ask why don't you just use a data class well this video isn't really about data classes this is about Dunder methods I know that this class could have easily been converted into a data class but again for all of these examples I'm just going to be showing you the functionality regarding the dunder methods anyway here we're going to type in defcor equality and that's going to take self and other which is also going to be self because we want to compare this fruit to another fruit and that will return to us a Boolean and you're not required to type any of this out I personally like to do it because it really helps me understand explicitly what I'm doing because otherwise if I see other like this personally I think you can just insert a string or literally anything I want but by adding self I know that this has to be another class of type fruit and Below all we need to do is specify a Boolean so if you want you can return that self name is equal to other dotame and this is the condition that this Dunder method is going to use to check whether two classes are equal which means if the name of Apple is equal to the name of apple fub1 and F3 are going to be considered the same object in this scenario that might be considered quite silly so what I'm going to do is return the self. dund dictionary which will compare everything in the class so self doore dictionary is equal to other doore dictionary and now if we were to scroll down and compare these two objects you'll see that F1 and F3 are going to be considered the same because both name and grams are equal but FS2 is not going to be considered the same or it's not going to be considered equal to fub1 because it has a different name and a different amount of grams moving on to dander method number two and again we're going to be using the exact same class except this time I'm going to create an instance called Apple with the name of apple and the grams set to 2,500 and what we're going to do inside here is specify a format than the method and in a previous video I annotated this as type any which was actually wrong because the only thing this can take is a string and it's going to return to us a string and with that being done I'm going to create a match statement and check what that format specifier contains so if the case is set to kilogram we're going to return the following string and here we're going to return self. GS / by 1,000 and that's going to be formatted to two decimal places kg and just like that we were able to create a format specifier for our fruit class and what that means is that if we were to print this apple in an F string and the F should go outside we can now use our custommade made format specifier with this Apple so we can pass in kg and the next time we run this we're going to get that Apple returned to us in kilogram and in this example I only inserted one but you can insert as many as you want such as pounds and a description and for all the other cases I just like to raise a value error because that just tells the user immediately that they entered a format specifier that we do not recognize or that we did not create the functionality for but now we can test out these other two cases by creating two more print statements and here we're going to add pounds and here we're going to add description and the next time we run this we should get those F strings printed to the console using our special format specifiers up next we have danda method number three and before we do anything with our class I'm just going to paste in this snippet of code or these lines of code and here all I did is create two dictionaries and combine them using this pipeline which in this case is the the union operator and this Union operator also works with sets as you can see here I created two sets and used the union operator with these two sets as well so that when we run the program we get everything combined with the dictionary we got all of the key and value pairs combined and with the set we just got all of the values combined so next we're going to recreate this functionality in our class and I'm going to remove all of this and replace it with these three instances and they all contain their respective information at the time being if we were to type in something such as combined and say that's a new fruit of Apple Union orange this would give us back an error because we did not Implement that functionality just yet so what we're going to do is go back to our class and implement this or functionality and other is going to be of type self and it's going to return self because we want to return a fruit back and the new name of type string is going to equal the F string of self. name and othername and the new grams of type float is going to equal self. GRS plus other. GRS so we're just combining everything and then we're going to return a new fruit with that new information so the name is going to be set to the new name and the grams are going to be set to the new GRS and now the next time we try to use this snippet of code we're not going to get an error back but we're actually going to get a new object back and since this representation is quite useless to us as a user I'm just going to quickly create a representation that is readable so let's go back to our class and here I'm going to paste in a repper Dunder method so that the next time we print the representation we will get back this this F string which means now we can run the script and what we will get back is a readable representation of our combined fruit as you can see we were able to perform that kind of Union operation that we did with sets and dictionaries with our custom class and we can also add a banana to the mix if that's what we want so Apple Union operator orange Union operator banana and the next time we run this we should get apple and orange and banana and the total gr of 5,000 or you can choose to only combine orange and banana it is up to you this Dunder method allows you to specify the functionality for that pipeline moving on to Dunder method number four and I'm actually going to be discussing two different Dunder methods here because if you are new to python chances are these two are going to be quite confusing the first time you see them so here we have a string Dunder method and a representation Dunder meth method and they're actually very similar I mean they both return to us information regarding what the fruit object actually is and the rule of thumb with using both of these Dunder methods is that with the string Dunder method you return something that's readable to the user so something that your grandmother could read and with the representation you return something that's useful for the developer as you can see here I'm returning something that looks like the fruit class itself being instantiated with those attributes and this is actually what you would get back if you were to use a data class so again this is very useful for the developer but for a user they might just want to see the information of the fruit not the actual fruit class by default your class is going to return the representation if you don't Define the representation and there's no string defined it's going to return to you that memory address of the class which doesn't tell us anything about what the class contains but to show you how both of these work I'm going to just create a list of fruits and that's going to contain the same fruits as always an apple an orange and a banana then below we can type in four fruit in fruits print the string of fruit and by default if you have defined a string dander method it's going to use that when you print your fruit so if we were to run this you're going to see the string version for each one of these and at this point the only way to get the representation back is to use the repper method on your fruit and then we can change that to repa and if we were to rerun this you'll get back the representations of all of these fruits and we can even compare them side by side so I'm just going to copy this and paste it directly under and the next time we run this we will see both the string representation and the actual representation side by side and again the string representation is meant to be something that is user friendly while the actual representation is meant to be something a bit more useful to the developer and one final note is that you're not required to specify the representation because by default we get back the memory address of the object as a representation so really if you are debugging and you just want a very simple message you can just use the string Dunder method but if you define neither it's just going to give you back the representation for both of them and finally it's time for the final Dunder method of the day and yes I've heard your prayers so I'm going to import from data classes the data class and instead of using this silly construct we're going to be using a data class instead so here we can just annotate this as at data class say that the keyword only should be set to true and that's going to simulate this asterisk and then all we have to do here is actually quite simple we just need to say that the name is going to be of type string and that the grams are going to be of type float so yes that was quite simple and it gives us a lot of functionality but again this video was meant to cover the dander methods not the differences between a data class and a normal class anyway the reason I created a data class of fruit is because under that I'm going to create a class called basket and this basket is going to contain an initializer which once again forces the user to pass in the arguments as keyword arguments so here we want to pass in some fruits which will be a list of type fruit and as always an initializer returns nothing then inside here we can type in self. fruits is equal to fruits then inside our main entry point I'm going to create a list of fruit and this list of fruit is going to contain some apples some oranges and a banana because we cannot live without a banana and with these fruits we can create a basket so basket of type basket will equal this basket of fruits which will equal fruits and now we have a basket of fruits and what I want to do with this basket is make it subscriptable and what that means is that if I were to print let's say the basket at the index of orange I'm going to want to get something back from that either an empty list or a list containing all of the oranges because at the time being we're going to get back the type error that the basket object is not subscriptable so let's change that and create the functionality that allows us to retrieve items from our basket and to do this all we need to do is Define not a backslash but a get item Thunder method and the item is going to be of type string and it's going to return to us a list of fruit and what I'm going to do inside here is return a very complicated list comprehension return the fruit for fruit in self. fruits if fruits. name. lower is equal to the item that we specify and all this does is return to us the fruit if it matches the item that we have specified and to make searching for it easier I lowered the name of each fruit because it would be quite annoying to have to capitalize Apple each time we searched for it because we are Human After All and we often make typing mistakes so sometimes even if you were to type in orange you might accidentally type in N with an uppercase n and that would ruin the entire search so we want to make sure that this just gets lowered before we search for it anyway now that we have implemented this functionality we can run our script and what we're going to get back are all the fruits that have the name of orange and to give us some extra information I'm going to create a new variable called matches which will be a list of type fruits and that's going to equal a basket that looks for Apple this time and we're going to print first that the matches are the matches and we're also going to print the total amount of matches so the length of matches and the next time we run this what we should get back are two matches and the actual matches now if we were to search for something that doesn't exist like 100 we should get zero matches back and you're not required to return a list you can actually return anything you want you can even raise an exception telling the user that that just does not exist and I know we did not search for the most important fruit so we're going to do that now so let's run this and see what we get back and of course the most satisfying result we could have gotten back is our banana so we have a total of one bananas anyways I hope you enjoyed this video do let me know in the comment section down below about your favorite Dunder methods and if you can include some Snippets of code I love to read them and discover new functionality but yeah otherwise with all that being said thanks for watching and I'll see you in the next video
Info
Channel: Indently
Views: 53,957
Rating: undefined out of 5
Keywords: pyton, pyhton, pythn
Id: y1ZWQQEe5PM
Channel Id: undefined
Length: 16min 9sec (969 seconds)
Published: Sun Apr 07 2024
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.