Python OOP Tutorial (Object Orientated Programming ) - Overriding Methods

Tech With Tim · Beginner ·🛠️ AI Tools & Apps ·7y ago

Key Takeaways

This video tutorial covers overloading methods in Python classes, such as __gt__, __len__, __eq__, and other Python builtins, to allow for operations and comparisons on created objects. It demonstrates how to define custom operations on classes using the `__add__`, `__sub__`, `__mul__`, and `__truediv__` methods.

Full Transcript

hey guys and welcome back to another object and classes tutorial video in today's video I'm gonna be going over loading default Python methods and why these are extremely useful now if you don't know what I'm talking about just stick around for one second and I will explain it so first of all I just want to talk about what I've already coded here I just have a very basic point class and you can see that our point object has three kind of attributes an X Y and then our coordinates which is self dot X and self dot Y we have very basic method that can simply move us by X and by Y when we type it in ok I've created four points down here and these are what we're going to use to kind of test up some examples and I'm about to create so in Python remember in my first video I was talking about the fact that if you create integer objects so for example I say like I equals five and like the Z equals five if I wanted to add these together all I simply have to do is well put a plus sign right and Python knows that this plus sign means okay these two things together now how does it know this and how does it know what to do well integers is pretty straightforward but what if we start doing things like strings right if you do S and then you go like six seven eight how but does Python know how to add these two strings together well it would make sense to it just appended on top but someone actually had to code this functionality in and that's exactly what we're gonna be doing in this video except with our custom point object okay and you'll see what I mean in just a second so pretty much what we want to eventually do at the end of this video is to be able to add multiply subtract in compare points without having to reference their attributes outside of the class so right now if I do p1 plus p2 our programs gonna crash because it doesn't know what that means but by the end of this video we're gonna be able to do that okay so that's what I'm gonna show you right now so in Python there's a bunch of defaults kind of operations and methods that you can apply on classes and by default that are not defined right on our point class if we try to add two things right now that doesn't make sense so what we're gonna do is add that method so to do this to add the add operation you're just going to do to find underscore underscore add okay and then in here you need to give another point object so what happens when I try to add a point and another point object well whatever we're going to return a new point okay that is simply equal to self dot X plus P dot X and then self dot y plus P del Y so what this is doing is since we're passing another point object so when we do like P 1 plus P 2 P 2 becomes P and P 1 becomes self so we're gonna grab the coordinates of P 1 add them to P 2 and return that in a new point object okay now the same works for subtract multiply and divide and for a few others as well so I'm just saying simply gonna copy this okay and paste it one more time and instead of add now you're probably guess I'm going to put sub and what this is going to do is allow us to subtract points so it's gonna be the exact same except now we are simply going to subtract the coordinates now with multiplication this one is simply defined underscore underscore mole underscore underscore and this going to allow us to use the asterisks or the star to multiply two different point objects so same thing it takes a point and in this case when we multiply points I could return a new point with multiplied coordinates but the way it actually works if you know anything about vectors is we're simply gonna return the scalar product which means you multiply the first two x-coordinates get a value in this case we get nine and then you actually add it to the y-coordinates multiplied together so in this case we'd have nine what do you call it plus eight and that would give us 17 we're not returning a new point object it's a scalar or like just a number value okay so we're gonna do here is we're gonna return self dot X multiplied by P dot X plus self-thought Y multiplied by P dot y and those are the three that I'm going to stick with right now and I'm gonna show you a bunch more that we can use to compare point objects using greater than equal then sign in just a second so I want to test if this is working so let's create a new point when say point five is equal to p1 plus p2 and I'm gonna say point six is equal to P for minus t1 okay and then we'll even go as far as creating p7 and applying p2 and p3 just to make sure everything's working so now I'm simply going to print to the screen p5 p6 and p7 and let's see what we get so you can see here I get main point object main point object and 9 now the way that this worked and the reason that we're not actually getting a coordinate value is because I have to show you another method that we can use so that this was actually gonna give us something meaningful because right now when we point printout our point objects right because 0.5 is a new point object because when we add point 1 and point 2 we are returned sorry a new point object right so if we want to make this meaningful and not just show us the address in memory where the point is stored which it currently is right now we need to add another method and this one is called STR okay what this is gonna do is this is going to be called every time we try to convert our point object into a string so when we try to print our point object it automatically looks for STR and if it doesn't find it it gives us this kind of gibberish right here but if it does find it it's simply going to well use the value that we returned so in this case we want to return I think we'd want to return from string probably the self dot coordinates right so I want it to look something like this we have brackets and then plus STR and then self dot X plus a comma plus STR self-thought Y and plus and then another bracket like this ok so now if I try to print point five point six at point seven you can see what we get and there we go so now instead of getting that gibberish we get 6 6 negative 3 and negative 3 now keep in mind you can make this anything you want but you do have to return a string value here for this to work ok so the next methods we're going to talk about I'm just gonna put them above string here just for good practice is going to be comparing two points so this is great now we can add we can subtract we can multiply but what if we want to compare so what if we want to see if point 1 is greater than 0.2 or if point 3 is greater than point well how do we do that we first have to determine how are we gonna compare points are we simply going to compare the exes and the Y's or are we gonna find like the magnitude of a point like what are we gonna do to compare which is larger in my case I want to find the length of a point from the origin so in this case the way this would work I think I can just bring up a little grid program here and just draw it for you quickly so if you have an origin like this okay I'm just using my mouse right now and you had a point here and a point here well from the origin this would have a distance and from the origin this would have distance obviously this could be like a distance of seven this could be a distance of two and seven would win right because we don't really care about the negatives if you had something all the way over here with a larger distance then what we would want that to win right so that's the way that we're gonna compare them and I'll talk about that and how we do that in one second so to compare we have four major comparisons I think that we can do and it goes I'll type down and we'll see so one of them is greater than and that is GT okay and you can do self and you also need another point object like this another one is greater than or equal to and greater than equal to simply GE okay and then the same thing we need P we have less than so define and you can probably guess LS or sorry LT what am I saying less then and then we also have less than or equal to so L II like that and we have one more and this is simply equal to so this is if we do the double equal sign then it's going to give us a comparison now in these methods we need to return a true or a false value so n greater then remember the way I said I wanted to compare them is to get like the magnitude of the point from the origin so I'm just gonna add a method in here I'm just gonna call it let's do length maybe okay and then in here I'm simply actually we don't need to take anything we're just going to return the math dot sqr T and I'm gonna import math right up here and this is simply how you get the length from the origin okay of self dot X ^ 2 + on again self dot why should the exponent - and this is gonna give us the length okay so import length so when I'm doing greater than I want to see if return self thought X first what am I saying self thought length is greater than P dot length like this okay and I believe we do actually need these square brackets here so all this is going to do is it's a boolean condition it says well if the length of our self is greater than the other length we'll then we're simply greater than so let's just copy this and put it in here and in this case we're just going to be greater than or equal sign because this is greater than or equal to copy this again change this around to less than and one more time and this is now just gonna be less than or equal to now if we're seeing if two things are equal to each other well that's pretty easy as well all we can do is simply take this or actually the way we're going to do this is just see if the coordinates are the same because if we try doing the math dot square root and we get like a large decimal number sometimes decimals kind of mess up in Python and they don't get the same precision so let's just return if self-thought x equals equals P dot X and self dot y equals equals P del Y because that would mean that they are at the same point right okay so let's do some comparisons now so let's just simply print if P 1 equals equals P 2 and then we'll print if p1 is greater than p2 and we can print if P 4 is less than or equal to p3 okay and just test these out okay so we get false true and true and you guys are welcome to mess around with these and kind of figure those out for yourself so I will show you I'm not going to go through all the methods because there's a lot of ones that you can overload but I'll show you how you can have a look at all of the different methods okay so I'm just gonna pull up a web page here that has like a large list of all of the kind of built-in methods that you can override or like what'd he call it overload there is a way in Python to like see all of them in print to the screen but I completely forget the command so I apologize when you guys knows that command please let me know in the comments because I've been looking for it I can't find it but anyways you can see here there's a ton like I think there's like a hundred or something of built-in ones that you can use like add sub mold if true to Florida can read through here and see what they all do some useful ones I will mention is probably Len I probably should have talked about that one but it's if you call the Len function on something so actually I'll show you Len really quickly just because I feel like I should have talked about so instead doing length here I could have just done define underscore underscore Len underscore underscore and what this would have done now is if I call like Len of p1 it's just gonna return whatever value I have here so mapped on square root okay that's like a really useful one too so I don't know why I didn't talk about that but anyways so I'll go back to this page for one second you can see real numbers slice slice can be useful if you're dealing with kind of like list objects that you're creating items and slices you can go through all these and kind of read them yourself I'm not going to talk about all of them because I'm sure these you guys probably want to end up using very much the ones that are very important are the ones I talked about so yeah so you can see built-ins like there's something you can do with like their built-ins to see them all alright and yeah I'll leave this link in the description in case any of you guys are interested in having a look at these but there is some way in Python again if you know that way please let me know ok guys so that's been it for this video in the next video I'm gonna be talking about static and class methods and then in the future video I'm gonna be talking about private private and public classes in Python so if you guys enjoyed the video please make sure you leave a like and subscribe and I'll see you again in the next one [Music]

Original Description

Classes and objects python tutorial #4. This video covers overloading methods such as __gt__, __len__, __eq__ and other python builtins to allow for operations and comparisons on your created objects. This is very cool and very useful! WEBSITE: https://techwithtim.net/tutorials/python-programming/classes-objects-in-python/overloading-methods/ ************************************************************** Support the Channel: https://www.patreon.com/techwithtim Twitter: https://twitter.com/TechWithTimm Join my discord server: https://discord.gg/pr2k55t ************************************************************** Please leave a LIKE and SUBSCRIBE for more content! Tags: - Tech With Tim - Python Tutorials - Object and Classes Tutorial - Objects and Classes Python - OOP Python - Object orientated python
Watch on YouTube ↗ (saves to browser)
Sign in to unlock AI tutor explanation · ⚡30

Playlist

Uploads from Tech With Tim · Tech With Tim · 0 of 60

← Previous Next →
1 A* Path Finding Algorithm(Visualization)
A* Path Finding Algorithm(Visualization)
Tech With Tim
2 Python Programming Tutorial #1 - Variables and Data Types
Python Programming Tutorial #1 - Variables and Data Types
Tech With Tim
3 Python Programming Tutorial #2 - Basic Operators and Input
Python Programming Tutorial #2 - Basic Operators and Input
Tech With Tim
4 Python Programming Tutorial #3 - Conditions
Python Programming Tutorial #3 - Conditions
Tech With Tim
5 Python Programming Tutorial #4 - IF/ELIF/ELSE
Python Programming Tutorial #4 - IF/ELIF/ELSE
Tech With Tim
6 Python Programming Tutorial #5 - Chained Conditionals and Nested Statements
Python Programming Tutorial #5 - Chained Conditionals and Nested Statements
Tech With Tim
7 Python Programming Tutorial #6 - For Loops
Python Programming Tutorial #6 - For Loops
Tech With Tim
8 Python Programming Tutorial #7 - While Loops
Python Programming Tutorial #7 - While Loops
Tech With Tim
9 Python Programming Tutorial #8 - Lists and Tuples
Python Programming Tutorial #8 - Lists and Tuples
Tech With Tim
10 Python Programming Tutorial #9 - Iteration by Item (For Loops Continued...)
Python Programming Tutorial #9 - Iteration by Item (For Loops Continued...)
Tech With Tim
11 Python Programming Tutorial #10 - String Methods
Python Programming Tutorial #10 - String Methods
Tech With Tim
12 How to Overclock a NVIDIA GPU
How to Overclock a NVIDIA GPU
Tech With Tim
13 Python Programming Tutorial #11 - Slice Operator
Python Programming Tutorial #11 - Slice Operator
Tech With Tim
14 Python Programming Tutorial #12 - Functions
Python Programming Tutorial #12 - Functions
Tech With Tim
15 Python Programming Tutorial #13 - How to Read a Text File
Python Programming Tutorial #13 - How to Read a Text File
Tech With Tim
16 Python Programming Tutorial #14 - Writing to a Text File
Python Programming Tutorial #14 - Writing to a Text File
Tech With Tim
17 Python Programming Tutorial #15 - Using .count() and .find()
Python Programming Tutorial #15 - Using .count() and .find()
Tech With Tim
18 Python Programming Tutorial #16 - Introduction to Modular Programming
Python Programming Tutorial #16 - Introduction to Modular Programming
Tech With Tim
19 Python Programming Tutorial #17 - Optional Parameters
Python Programming Tutorial #17 - Optional Parameters
Tech With Tim
20 Python Programming Tutorial #18 - Try and Except (Python Error Handling)
Python Programming Tutorial #18 - Try and Except (Python Error Handling)
Tech With Tim
21 Python Programming Tutorial #19 - Global vs Local Variables
Python Programming Tutorial #19 - Global vs Local Variables
Tech With Tim
22 Python Programming Tutorial #20 - Classes and Objects
Python Programming Tutorial #20 - Classes and Objects
Tech With Tim
23 Cool VBS Script to Prank Your Friends!
Cool VBS Script to Prank Your Friends!
Tech With Tim
24 How to Overclock an AMD GPU
How to Overclock an AMD GPU
Tech With Tim
25 Best GPU'S For Mining Ethereum (2018)
Best GPU'S For Mining Ethereum (2018)
Tech With Tim
26 Recursion and Memoization Tutorial Python
Recursion and Memoization Tutorial Python
Tech With Tim
27 Ethereum Mining Rig - Hardware Guide
Ethereum Mining Rig - Hardware Guide
Tech With Tim
28 Pygame Tutorial #1 - Basic Movement and Key Presses
Pygame Tutorial #1 - Basic Movement and Key Presses
Tech With Tim
29 How to Install Pygame (Windows 8/10)
How to Install Pygame (Windows 8/10)
Tech With Tim
30 How to Trade Your Cryptocurrency (Bitcoin, Ethereum etc.) For Cash!
How to Trade Your Cryptocurrency (Bitcoin, Ethereum etc.) For Cash!
Tech With Tim
31 How to Mine Ethereum 2018 - WORKING (Super-Easy)
How to Mine Ethereum 2018 - WORKING (Super-Easy)
Tech With Tim
32 Microphone Comparison - $10 Mic vs $150 Mic (Blue Yeti USB)
Microphone Comparison - $10 Mic vs $150 Mic (Blue Yeti USB)
Tech With Tim
33 Pygame Tutorial #2 - Jumping and Boundaries
Pygame Tutorial #2 - Jumping and Boundaries
Tech With Tim
34 Pygame Tutorial #3 - Character Animation & Sprites
Pygame Tutorial #3 - Character Animation & Sprites
Tech With Tim
35 Pygame Tutorial #4 - Optimization & OOP
Pygame Tutorial #4 - Optimization & OOP
Tech With Tim
36 OBS Studio Tutorial - Best OBS Settings
OBS Studio Tutorial - Best OBS Settings
Tech With Tim
37 Linear Search Algorithm - Python Example and Code
Linear Search Algorithm - Python Example and Code
Tech With Tim
38 Make Any Mic Sound AMAZING! (WITH OBS)
Make Any Mic Sound AMAZING! (WITH OBS)
Tech With Tim
39 Binary Search Algorithm - Python Example & Code
Binary Search Algorithm - Python Example & Code
Tech With Tim
40 Pygame Tutorial #5 - Projectiles
Pygame Tutorial #5 - Projectiles
Tech With Tim
41 Pygame Game - Mini Golf
Pygame Game - Mini Golf
Tech With Tim
42 Pygame Tutorial - Projectile Motion (Part 1)
Pygame Tutorial - Projectile Motion (Part 1)
Tech With Tim
43 Pygame Tutorial - Projectile Motion (Part 2)
Pygame Tutorial - Projectile Motion (Part 2)
Tech With Tim
44 Pygame Tutorial #6 - Enemies
Pygame Tutorial #6 - Enemies
Tech With Tim
45 Pygame Tutorial #7 - Collision and Hit Boxes
Pygame Tutorial #7 - Collision and Hit Boxes
Tech With Tim
46 Pygame Tutorial #8 - Scoring and Health Bars
Pygame Tutorial #8 - Scoring and Health Bars
Tech With Tim
47 Cloud Mining vs. Hardware Mining - 2018
Cloud Mining vs. Hardware Mining - 2018
Tech With Tim
48 How to Install Pygame on Mac OSX (Fast-Simple)
How to Install Pygame on Mac OSX (Fast-Simple)
Tech With Tim
49 Pygame Tutorial #9 - Sound Effects, Music & More Collision
Pygame Tutorial #9 - Sound Effects, Music & More Collision
Tech With Tim
50 Pygame Tutorial #10 - Finishing Touches & Next Steps
Pygame Tutorial #10 - Finishing Touches & Next Steps
Tech With Tim
51 How to Fade Your Screen in Pygame [CODE IN DESCRIPTION]
How to Fade Your Screen in Pygame [CODE IN DESCRIPTION]
Tech With Tim
52 How to Create a Button in Pygame [CODE IN DESCRIPTION]
How to Create a Button in Pygame [CODE IN DESCRIPTION]
Tech With Tim
53 Pygame Side-Scroller Tutorial #1 - Scrolling Background/Character Movement
Pygame Side-Scroller Tutorial #1 - Scrolling Background/Character Movement
Tech With Tim
54 Pygame Side-Scroller Tutorial #2 - Random Object Generation
Pygame Side-Scroller Tutorial #2 - Random Object Generation
Tech With Tim
55 Pygame Side-Scroller Tutorial #3 - Collision
Pygame Side-Scroller Tutorial #3 - Collision
Tech With Tim
56 Pygame Side-Scroller Tutorial #4 - Scoring and End Screen
Pygame Side-Scroller Tutorial #4 - Scoring and End Screen
Tech With Tim
57 How to Create A Message Box in Python - Tkinter
How to Create A Message Box in Python - Tkinter
Tech With Tim
58 Is Ethereum Mining Still Profitable - Is It Worth It (April 2018)
Is Ethereum Mining Still Profitable - Is It Worth It (April 2018)
Tech With Tim
59 How to Run MAC OSX on a WINDOWS PC (Clover Boot-loader)
How to Run MAC OSX on a WINDOWS PC (Clover Boot-loader)
Tech With Tim
60 Programming Problem #1 - Alphabet Soup (Beginner/Novice)
Programming Problem #1 - Alphabet Soup (Beginner/Novice)
Tech With Tim

This video tutorial teaches how to overload methods in Python classes to allow for custom operations and comparisons on created objects. It covers how to define custom operations using the `__add__`, `__sub__`, `__mul__`, and `__truediv__` methods and how to override methods to compare points.

Key Takeaways
  1. Define the `__add__` method to add two points
  2. Define the `__sub__` method to subtract two points
  3. Define the `__mul__` method to multiply two points
  4. Define the `__truediv__` method to divide two points
  5. Override methods to compare points (GT, GE, LT, LE, EQ)
💡 Overloading methods in Python classes allows for custom operations and comparisons on created objects, making it a powerful tool for object-oriented programming.

Related AI Lessons

Up next
I Asked ChatGPT to Apply to 500 Jobs (8 Interviews in 48 Hours)
Sabrina Ramonov 🍄
Watch →