Python OOP Tutorial 5: Special (Magic/Dunder) Methods
Key Takeaways
This video tutorial covers special methods in Python, also known as magic or dunder methods, which allow for built-in behavior emulation and operator overloading. Corey Schafer demonstrates how to use these methods to customize object behavior and implement arithmetic operations.
Full Transcript
hey everybody how's it going in this video we'll be learning about special methods that we can use within our classes and some people call these magic methods now these special methods allow us to emulate some built-in Behavior within Python and it's also how we implement operat or overloading so what I mean by that is for example when we add two integers together so down here I'm going to print out 1 plus two and when we add two strings together so I'm going to print out a plus b if I run this code then you can see that the behavior when we add two strings together is different than when we add two integers together so the strings were just concatenated and the integers were actually added together so depending on what objects you're working with the addition actually has different behavior um and also if we were to print out our employee instance here then you can see that we just get this vague employee object and it would be nice if we could change this Behavior to print out something a little bit more userfriendly and that's what these special methods are going to allow us to do so by defining our own special methods we'll be able to change some of this uh built-in behavior and operations so these special methods are always surrounded by double underscores so a lot of people call these double underscores Dunder so if you ever hear someone say something like Dunder a nit then they mean a nit surrounded by double underscores So speaking of Dunder a knit that is a special method that we've already been using and are familiar with and it's probably the first and most common special method that people use when working with classes so just like we learned in previous videos this special Dunder a nit method me is implicitly called when we create our employee objects here and it comes in and sets all of our attributes for us so let's take a look at some other common special methods so two more common special methods that we should probably always Implement are this Dunder re and Dunder St Str now these are what are implicitly called anytime we run re on one of our objects or Str STR on one of our objects and these are what we're going to used to fix our problem of printing out this vague employee object when we printed out our employee instance here now I have an earlier video on the difference between these two methods um but in short re is meant to be an unambiguous representation of the object and should be used for debugging and logging and things like that it's really meant to be seen by other developers and Str Str is meant to be more of a readable representation of an object and is meant to be used as a display to the end user so let's go ahead and write code for these and take a look at the difference so first we want to be sure to at least have an re method because if we have this without an Str Str then calling Str STR on an employee we'll just use the re as a fallback so it's good to have this as a minimum now A good rule of thumb when creating this method is to try to display something that you can copy and paste back in the python code that would recreate that same object so for example here if I was to come in here and return um so we would want this to be something that we could use to recreate this object so I'm going to say employee and then in quotes I'm just going to put a uh placeholder there and I'm going to do quotes again for the last name and then I'll do another placeholder for the pay and then I'll just go ahead and create a format string here and let's do self first self. last and self. pay so again what I was doing here is that I was trying to return a string that I can use to recreate the object so to show you what I mean let's go ahead and print out this employee one again so first I'm just going to go ahead and comment out these lines here now remember when I printed out this instance before then we got this vague employee uh output here but now whenever I rerun this with this rpr method now you can see that it returned the string that we specified in our rpr method and you can see how if I wanted to recreate this employee object then I can just copy this output and it's the exact same thing that we used to create that employee to begin with so now let's go ahead and fill in the code for our Dunder string method so this is meant to be more readable for an end user so this is a little bit more arbitrary but to print out this employee let's see I'll just say something like uh I'll do a return and I'll do a placeholder for their full name and a placeholder for their email and then I'll just go ahead and pass those in so I'll do self. full name and then I'll also do uh self. email so now if I print out this employee object again now it should use that Dunder St method instead so now when we print out that employee object it's printing out the employees full name and email address now we can still access the rpr and the Str Str specifically if I was to go in here and print both of these out and then let me go ahead and close those off and I'll comment out that now really when we run this rpr and Str Str what's actually going on in the background is that it's directly calling those special methods so let me go ahead and copy these out and instead it's actually calling this _ and then if I go ahead and grab this then I'll also print out the Str Str and if I run that then you can see that we got the exact same object by calling those directly so these two special methods allow us to change how our objects are printed and displayed now to be honest unless you're writing some more complicated classes these three methods of anit re and Str Str uh will be the ones that you'll probably use most often but let's go ahead and look at a few more just so we can get an idea of how these work now there are also a lot of special methods for arithmetic um so like we saw before when we added those two integers together so if I was to say print one plus print two now if I go ahead and run this now what this is actually doing is it's using a special method in the background called Dunder ad so I can actually access this uh directly if I use the integer object I can do Dunder add and I can pass in arguments of one and two so if I run that then you can see that that gives us the same result and strings are actually using their own Dunder ad method so if I use a string object and do a Dunder ad and pass in a character of a and a character of B and run that then you can see that the strings Dunder ad actually concats those together so we can actually customize how addition works for our objects uh by creating that Dunder ad method so let's say that with our employee class we wanted to be able to calculate total salaries just by adding employees together now that's kind of a contrived example because if I was to make a class like that in real life then it's probably better to be explicit about what you're adding together uh but just for the sake of this example let's go ahead and see how we do this and we'll look at some better real world examples uh from the standard Library here in just a minute so if I wanted to add two employees together and have the result be their combined salaries then we're going to have to create a Dunder ad method so I'll go ahead and do that and this is going to take in self which is going to be what's on the left side of the addition and other which will be on the right side of the addition and for this example we're just going to assume that these are both employee objects so we want to return self. pay and added to other. pay so when we add two employees together it's going to give us their combined pay added together so let's go ahead and see if this works so here I can just print out employee one plus employee 2 and if I go ahead and run that you can see that when we added these two employee objects together that it gave us their combined salaries now if we didn't have this Dunder ad method and I copy and comment out that then you can see if I try to run that then it gives us an error here and it says that it doesn't know how to add these two employees together um so if we put that back in then we are telling it how we want to add these employees together so if I run that then you can see that that works now there are all kinds of these special methods for arithmetic and if I go to the documentation here you can see that there are uh special methods for subtracting multiplying uh dividing and plenty of others so so let's go ahead and run through one more example here before we look at some of these uh real world examples in the standard Library so if you have ever used the Len function to check the length of a list or a string now this is also a special method so if I wanted to print the length of a string so for example I could say print Len of the string test and let me go ahead and get rid of that print statement there if I run that you can see that that string is four characters long now this is also just using a special Dunder method in the background so if instead I was to print test and on that string object I could actually specifically run that Dunder length method and if I run that then you can see that we get the same result so if we want this Lin function to work on our objects then we'll have to create a Dunder ly method um so let's say that for example when we ran Lyn on our employee instance that we wanted it to return the total number of characters in their full name and maybe this could be useful if someone's writing a document and needs to know how many characters the employees name will take up so I can create this Dunder Lin method just by saying def Dunder Lin and this is only going to take in self and now for this I just want to return the link of self. full name so now we can actually use this Lin fun function on our objects so if I was to pass in employee one here and print that out then you can see that we get 13 characters when their full name is printed out now there are a ton of other special methods that we could go over so you can use these to customize how objects are compared how they check for equality and a lot of other useful stuff that we're not going to be able to fit into one video but if you go to the documentation then you can see a short description of all the ones that you can use and I'll put a link to that page in the description section below so now let's go ahead and take a look at some real world examples in the standard Library so that we can see how useful these can be in real code so I've got the datetime module pulled up here so in the datetime module I'm just going to do a search here for Dunder ad so the first result that we land on here is from the time Delta class and you can see that they are uh checking if the other object that they're adding against is another time Delta and to add those together they are just returning another time Delta with the days seconds and micros seconds added up from both of those and if the other object isn't a Time Delta then it's going to come down here to this return not implemented now that's something that we didn't go over in our examples but basically when they return not implemented uh they don't want to throw an error because the other object might know how to handle that operation so returning not implemented is a way to fall back on the other object to see if it knows how to handle the operation and if none of them know how to handle it then it'll eventually throw an error okay so let's go ahead and take another look at another example so I'm going to search here for the date class so now we're here within the date class and I'm just going to scroll down here a little bit and here we can see that they have their Dunder re method and you can see that they give some examples of what the output should look like and just like we talked about earlier uh it looks just like how you would create a date object and if we scroll down a little bit further here now here we can see that they're setting their Dunder string method equal to the iso format function so when you print the date it'll actually print out the iso format so that's pretty interesting so you can see how learning about these things makes it a little less intimidating to look around in the standard library and it makes it a little easier to just be able to look under the hood and see what's going on now don't get me wrong there's a lot of complex code in here but learning how these special methods work is a big step towards better understanding a lot of what's going on in here okay so I think that is going to do it for this video I hope this gave you a better idea of how these special methods work and what's going on in the background when you're performing some of these operations but if you do have any questions about what we covered in the video then just feel free to ask in the comment 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 if 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 special methods. These are also called magic or dunder methods. These methods allow us to emulate built-in types or implement operator overloading. These can be extremely powerful if used correctly. We will start by writing a few special methods of our own and then look at how some of them are used in the Standard Library. Let's get started.
Python Docs: https://docs.python.org/3/reference/datamodel.html#special-method-names
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