Тёмный

Python OOP Tutorial (Object Orientated Programming ) - Overriding Methods 

Tech With Tim
Подписаться 1,6 млн
Просмотров 84 тыс.
50% 1

Опубликовано:

 

30 окт 2024

Поделиться:

Ссылка:

Скачать:

Готовим ссылку...

Добавить в:

Мой плейлист
Посмотреть позже
Комментарии : 152   
@christianturner1438
@christianturner1438 5 лет назад
first
@wongkingshun
@wongkingshun Год назад
why "(" + str(self.x) what is the plus before the str(self.x) implies? I thought it should be " , " which means the p.x plus self.x str instead of "("
@mejiab19
@mejiab19 4 года назад
I notice a lot of people seem to be confused with how these functions seem to be triggered without calling them. Remember these are built in functions that have already been defined. By redefining each of the functions Tim has showed in this video, when the addition, subtraction, multiplication etc is used within this program the redefined or in other words "overloaded" functions like __add__, __sub__ etc will be used when the corresponding arithmetic operators are used like +, - , * etc. Now for strings, the "+" is used to concatenate two strings together. (Just to clear that up for those that asked this question)
@OM-el6oy
@OM-el6oy 4 года назад
Thank you so much for this explanation! This confused me so much, I thought there was something mythical going on lol.
@mejiab19
@mejiab19 4 года назад
@@OM-el6oy Np! Glad my explanation was able to help you! 😊
@shyren_more
@shyren_more 4 года назад
Thanks for explaining the video in simpler words, one more question, could you tell why certain methods inside class start with underscores eg: __func__ ()??
@mejiab19
@mejiab19 4 года назад
@@shyren_more So the methods that start with underscores are to let python know "Hey those methods already exist" hence built in methods but are methods in which we are able to redefine the definition of that method within this particular class.
@all4o4you59
@all4o4you59 2 года назад
overloading methods like: _add__, __sub_, etc. so in this example where are overriding methods? another question is if we can create new operators that do not exist in python with these methods?
@Sciencedoneright
@Sciencedoneright 3 года назад
8:58 for people who didn't understand, it is the Pythagorean theorem; a² + b² = c²
@endaoyuan9565
@endaoyuan9565 8 месяцев назад
Ya, just though of that, I am confuse when first seeing. After trying to find out why, i though of Pythagorean theorem lol.
@arditsaliasi6515
@arditsaliasi6515 14 дней назад
The length is just the Euclidean length, which is based of course in the Pythagorean theorem for R². You can basically generalize it for any space Rn.
@rrl9786
@rrl9786 5 лет назад
Leaving this here for anyone who sees this in the future: I *think* there's a mistake toward the end of the video, when Tim quickly says that he could have used __len__ instead of the length() method that he made. I'm not sure if I'm understanding 100% correctly, but I don't think this makes sense. __len__ looks for the number of items (attributes) in an object. In this case, every Point() object has two attributes. The length() method, on the other hand, is literally a mathematical formula for determining the distance of a point from the origin 0,0. These are two completely different things. For example, if we have Point(1,2), the __len__ of that is 2, because there are two attributes (x and y). However, the *length*, which is a numerical value as determined by that formula, would be sqrt(1**2 + 2**2), which is about 2.23. This is why some of you are getting errors about float types not being integers. __len__ is trying to find the integer value of how many attributes are in the object, whereas length() is an actual float number derived from a calculation. Other than that this is rock solid, all of Tim's videos are amazing. I have learned more about OOP in a couple hours watching these than I did taking a Python Bootcamp course from Udemy. Tim, if you ever read this, you seriously rock. You are going to go far in the CS world.
@nicop175
@nicop175 4 года назад
Experienced the same issue. Thanks for sharing.
@thiagofpmr
@thiagofpmr 4 года назад
Actually, the only issue is that the __len__ method must always return an Int. That's pretty much all of it. If you take the result of that formula he used for the length of the vector (which is a Float) and use int() on it, you won't get type errors (which kinda means that, for this use, __len__ isn't ideal).
@zukozaider5804
@zukozaider5804 4 года назад
Not exactly, he actually overwrote the __len__ with the code for length(), so it will provide the same functionality
@branded6346
@branded6346 4 года назад
As a beginner, this tutorial has been hard for me. but thanks Tim.. i'm learning!
@vaibhavkrkm
@vaibhavkrkm 4 года назад
One tip : If you are a beginner, I understand these concepts would be hard to understand, so my tip is make some projects with basic concepts of Object-Oriented Programming and then start defining these special methods in your new and a bit advanced projects if they are needed..
@absolutedgefindout726
@absolutedgefindout726 5 лет назад
This is it as you said ... 'dir(__builtins__)' to get all of 'em
@TechWithTim
@TechWithTim 5 лет назад
Thank you!
@freezaki7302
@freezaki7302 4 года назад
@@TechWithTim this just shows the types of errors and warnings??
@freezaki7302
@freezaki7302 4 года назад
this just shows the type of errors and warnings??
@subarutendou
@subarutendou 4 года назад
@@freezaki7302 type >>>help (__builtins__)
@freezaki7302
@freezaki7302 4 года назад
@@subarutendou ar thank you for responding.
@xarcu
@xarcu 3 года назад
1:21 Tim: "you'll see what i mean in just a second". 5 hours later, me: "this is a very long second..." Anyways bro, my ineptitude not yours. You're the best out there thanks a million for all your help!
@mcd123
@mcd123 2 года назад
Thanks for creating these for us at 7AM when most are still asleep!! 💪🏼🙏🏼🙏🏼
@beachwave5705
@beachwave5705 Год назад
one thing i think you should mention is how it is important to define certain functions before others, like if you were to write the def length function you created after all the comparisons, the boolean value wouldn't be able to execute true or false if it didn't have a way to use your length function
@vagifk2864
@vagifk2864 4 года назад
No need to import math: (self.x**2 + self.y**2)**(1/2)
@ThomasDeWolf-tt6xd
@ThomasDeWolf-tt6xd 3 года назад
why would you not just import math tho??
@vagifk2864
@vagifk2864 3 года назад
@@ThomasDeWolf-tt6xd the principle of Occam's
@ThomasDeWolf-tt6xd
@ThomasDeWolf-tt6xd 3 года назад
@@vagifk2864 importing math is way more simple right? thats basically what the principle means: the simple solution is the best one
@vagifk2864
@vagifk2864 3 года назад
@@ThomasDeWolf-tt6xd not always
@guyonYTube
@guyonYTube 3 года назад
@@vagifk2864 Well atleast in this case for efficiency, but it is maybe better to do "from math import sqrt" and optionally "del sqrt" for larger projects.
@gerjenvd7129
@gerjenvd7129 3 года назад
I think you're wrong about your def __eq__. They can still have the same length if their x or y coordinates are the same. For example: if they were like this: (3,2) and (2,3). Still great videos and good explanation, though.
@amindiafi4948
@amindiafi4948 Год назад
Also (-2, -2) and (2, 2) returns False so no positive constraints
@scatterrealms5166
@scatterrealms5166 9 месяцев назад
@@amindiafi4948 This is what I was thinking you'd need to use abs() on these values
@endaoyuan9565
@endaoyuan9565 8 месяцев назад
Instead of using built in function, I did used print(p1.__div__(p2)) to do division function. It did result same as the built in function, just to show there is another method to do the operation if the class had these methods :)
@graham287
@graham287 4 года назад
W OOPs. Too involved for me. I just made the __add__ method print text "Hello". Said the same thing but a lot shorter. But, saying that, I didn't know you could override built in methods and will be tinkering with it later. Thanks for another great insight Tim.
@Cankuification
@Cankuification 5 лет назад
What goes around will come back around for you soon,Tim, I believe
@TechWithTim
@TechWithTim 5 лет назад
:)
@damonchase1922
@damonchase1922 3 года назад
tim you are so good at doing these YT tutorials.
@dv7045
@dv7045 4 года назад
this one is really hard ))
@cristinocanga
@cristinocanga 2 года назад
10:56 The function it's called dir(class)
@gaia38ant
@gaia38ant 2 года назад
dir('class') for me
@teacherinthailan6441
@teacherinthailan6441 3 года назад
Excellent lesson Tim. Thank you so much. You are an awesome teacher.
@halamadrid5238
@halamadrid5238 3 года назад
The equals method is wrong because two points can have the same length without being the same coordinate. For example (5,5) and (-5,-5), they have the same length but they are two different coordinates
@theperkyfellow
@theperkyfellow 4 года назад
This is soooooooo good! Truly Professional! Thanks Tim
@daveanvs
@daveanvs Год назад
Great explanation
@parthjain263
@parthjain263 2 года назад
It might not be in then but you can now use @dataclass which pretty much initializes everything so you dont have to type it out.
@nicolez7132
@nicolez7132 13 часов назад
best course!
@nialyavuzturk2555
@nialyavuzturk2555 3 года назад
at the end of the video, if len(p1) doesn't work for you try print(p1.__len__()) It should work
@avvn9331
@avvn9331 5 лет назад
Very useful video sir, thank you
@pawejerzyna5674
@pawejerzyna5674 Год назад
Great video
@wongkingshun
@wongkingshun Год назад
For p1, (3,4) FOr p2, (3,2) So the first 3 is self.x and the second 3 is p.x Nd for the 4 is self.y and 2 is the p.y right? So, why the second x is p.x?
@asimmohammed6978
@asimmohammed6978 Год назад
Thanks for the video. 🙏🙏🏿
@rojadsorum9515
@rojadsorum9515 4 года назад
Initially he is showing operator overload
@anandhraj1952
@anandhraj1952 2 месяца назад
You are so cool
@simasilia
@simasilia Год назад
that was so helpful,thanks
@facilvenir
@facilvenir 3 года назад
Great tutorial and serie. It's very good for a beginner like me. One question. the page you mention at the end is shut down. Any ideas where I can find something similar?
@Sciencedoneright
@Sciencedoneright 3 года назад
12:18 It's NOT IN THE DESCRIPTION!
@sinanm6634
@sinanm6634 5 лет назад
Thank you Tim for this great tutorial. Its very awesome, but i didnt understood why the "move" method is standing for.
@beaconsys
@beaconsys 4 года назад
SinanM, I think it stands for "moving the original point horizontally by x, and vertically by y, where x and y is the parameters passed by method calls.
@HenryKHLai
@HenryKHLai 2 года назад
Try this code def move(self, a, b): self.coords = (self.x+a, self.y+b) The coords attribute will be updated
@motomatt5040
@motomatt5040 2 месяца назад
an f string would be much more readable for the __str__, this was released in python 3.6. return f"({self.x},{self.y})"
@pedropc5824
@pedropc5824 4 года назад
I love this series but this episode was so hard to understand
@Sciencedoneright
@Sciencedoneright 3 года назад
slightly yes!
@BiologyIsHot
@BiologyIsHot 3 года назад
I wonder if people find it hard because of the linear algebra concepts he used as examples or because the actual approach? Because I have some modest physics background the linear algebra example made it really click
@jacob_ha
@jacob_ha 3 года назад
same :(
@djfoo000
@djfoo000 4 года назад
I disagree with the way you defined the "equals" method. The other comparators were comparing the scalar lengths (magnitude), while the "equals" method seem to be defined to compare identities? For example, length(2,2) == length(-2, -2), but clearly they are not the same point. The method as defined in your video would be more suited to an "is" method or something else. This is an identity vs equality issue.
@aminuabdusalam3086
@aminuabdusalam3086 4 года назад
I think I understand what you're saying, but it seems like the expression tim used for the equals would actually work. I 'd really be honored if you reply with more insights on what you mean.
@muriloescher8607
@muriloescher8607 4 года назад
@@aminuabdusalam3086 I'm not the original commenter, but felt I could help. Just simply think about mirrored points in relation to the origin. For example (3, 3) and (-3, -3). They have different coordinates, however, the length of both are equal. Or also (3, 4) and (4, 3). You'll see both lengths are equal to 5, despite the x and y values not being the same. Had Tim used the expression he used for the others (sqrt(x² + y²)), it would indeed work, but he changed it. I basically just repeated what OP said, but hope it helped.
@aminuabdusalam3086
@aminuabdusalam3086 4 года назад
@@muriloescher8607 Thanks a lot. I really appreciate that you took time to respond to my question.
@hankblack783
@hankblack783 2 года назад
I think this is an awesome series, but in this case I agree with djfoo000. We need to be clear what we mean by p1 > p2, p1 < 2 and p1 = p2. if we mean the length of the vector (which is what was used to calculate p1 > p2 and p1 < p2), then we can't say p1 = p2 only when p1.x == p2.x and p1.y == p2.y, as there are an infinite number of vectors with the same length but the equality test only allows for the two vectors to be the same vector. If it were just a matter of rounding errors and how the calculations were done, then the definitions should be done in this order: def __eq__(self, p): # put the "better" definition of the = operator here def __ge__(self,p): return (self.length() > p.length()) or (self == p)) ;;; def __le__(self.[): return (self.length() < p.length) or (self == p) One thing I am wondering about though, is should "import math" be done at the class level rather than within the length method? Does it make a difference performance wise? (I know you could've also skipped importing math and just used exponents with 1/2 for the square root , but my question is more about when you do need to import a module, where is the best place to put the import statement).
@qwertyguy1556
@qwertyguy1556 3 года назад
def __eq__(self,p): return self.x == p.x and self.y == p.y actually this is not going to work imagine that the -len- as a variable which hold a specific distance from (0,0), the collection of dots with this distance are the circumference of a circle with center of (0,0) and -len- as radius so that gonna be a bunch of dots but you will return True only when the points are same example of cases that True was supposed to be returned (3,2) == (-3,2) (3,6) == (6,3) ... although it was a nice tutorial series. Good luck ; )
@rulofmg
@rulofmg 5 лет назад
Im still a newbie and Im starting to code a bot as a practice, is it important to code it as a class structure right away? I dont know yet if its going to be complicated later on. Can you maybe make a tutorial on the best practice to start a project and develop?
@kubic-c3186
@kubic-c3186 4 года назад
Are you making one bot or mulitple bots
@RS-eo5ft
@RS-eo5ft 4 года назад
It's been so difficult for beginners like me...😮😮
@יעלליפשיץ-כ2נ
@יעלליפשיץ-כ2נ 3 года назад
Thank you!
@all4o4you59
@all4o4you59 2 года назад
overloading methods like: _add__, __sub_, etc. so in this example where are overriding methods? another question is if we can create new operators that do not exist in python with these methods?
@abuturabsayed
@abuturabsayed 3 года назад
it was ok till the point where you defined the length method. It was returning Math.sqrt(self.x**2+self.y**2). But then how did you invoke the length method on p? Can you please elaborate on that?
@moe42937
@moe42937 5 лет назад
You are amazing Bro
@vipdeveloper265
@vipdeveloper265 4 года назад
does __str__ method always used for any type of printing integers?
@BrodyBikez
@BrodyBikez 4 года назад
because he was printing coordinates which are a different type of data point. not just an integer i believe.
@aryansaxena4978
@aryansaxena4978 4 года назад
Thanks man
@kunalsaha12
@kunalsaha12 7 месяцев назад
why is this bit of code in the initialisation: self.coords = (self.x, self.y)??
@pauivorra1819
@pauivorra1819 3 года назад
What is your outro music? Want to know the title because it sounds excellent
@KshitijKale
@KshitijKale 4 года назад
easy, easy, easy never been this easy
@sean7260
@sean7260 5 лет назад
Amazing ass videos man
@TechWithTim
@TechWithTim 5 лет назад
Thank you!
@wongkingshun
@wongkingshun Год назад
what is p.x stands for?
@tcironbear21
@tcironbear21 4 года назад
Why did you not make Point class inherit from from "Object" like in prior lessons?
@ahmedhakam4895
@ahmedhakam4895 2 года назад
{ P1+P2 = P1.add(P2) } is that right ?
@burrowsforge3538
@burrowsforge3538 9 месяцев назад
The last few tutorials I was able to follow along but you lost me here at about 2 minutes in. I've tried rewatching it a couple times but it's just too much of a jump for me. Hopefully at some point I'll be able to understand what is happening here.
@carlospaiva7903
@carlospaiva7903 4 года назад
Thanks
@Heck-ed6sr
@Heck-ed6sr 4 года назад
what does x=0 and y=0 mean in the parameters of the first method 'def __init__(self, x=0, y=0)'?
@Heck-ed6sr
@Heck-ed6sr 4 года назад
To those who are wondering as well, found out it makes it such that x and y takes on the default value of 0 and become optional parameters
@adityanarayan9968
@adityanarayan9968 4 года назад
What is the purpose of returning an object in this context using __add__ method overloading?
@paolomaimone4482
@paolomaimone4482 3 года назад
i just realized i only watched shitty oop tutorial until now: mindblown
@davidaguirre6614
@davidaguirre6614 4 года назад
please help i dont understand what the method def move(self, x, y) does
@RoadToTendrils
@RoadToTendrils 4 года назад
great course but about this video.. I'm not understand how the functions triggered without calling them
@MayorMuric
@MayorMuric 4 года назад
I'd say due to a similar behavior to built-in methods such as __init__. As in when you initialize the class it triggers them. If anyone would confirm or clarify, by all means.
@rishabhroy230
@rishabhroy230 4 года назад
Yeah , like the __str__ was not called but it did its job..how?
@MayorMuric
@MayorMuric 4 года назад
@@rishabhroy230 Try to go in depth into built-in methods, overloading and the return keyword. One of them or the combination of them will probably give you insight. Pay attention to how he is using () to invoke the instances of the classes as well. Additionally, he is using print. __str__ can be used to manipulate the string you print when printing your class/instance.
@ahmedhakam4895
@ahmedhakam4895 2 года назад
Java is more specific and so organized there's no way for confusion in it
@joana1746
@joana1746 4 года назад
Shouldn't the title of video be 'Overriding'?
@donaldslowik5009
@donaldslowik5009 4 года назад
Nope, that would be when you redefine a method in a child class that overrides (hides) the inherited def in a parent. Here we are overloading some standard python operators so that they apply to your home spun objects.
@navneetmann1411
@navneetmann1411 4 года назад
But isn't he overriding all these methods which are already written in object class? Little confused here
@rojadsorum9515
@rojadsorum9515 4 года назад
How P2 becomes p and .....
@alfianalamsyah3442
@alfianalamsyah3442 4 года назад
XD yeah i didnt get it also
@rogerwilliams6326
@rogerwilliams6326 4 года назад
at 10.26 the def __eq__ is wrong... cause if we have p1(2, 1) and p2(1, 2) the lenght is the same but neither p.x and self.x are equal or p.y and self.y
@gathikjindal3934
@gathikjindal3934 4 года назад
I din' t understand the __str__ function you made.
@kushkhamesra9453
@kushkhamesra9453 4 года назад
just converts a location in memory into an understandable string.
@techeye7005
@techeye7005 2 года назад
I can't understand why we are using (def move) in the program can anyone explain it to me
@Msr94145
@Msr94145 3 года назад
why do we need the sqtr? return math.sqrt(self.x**2 + self.y**2) i cannot understand this...
@kathanchaudhari6303
@kathanchaudhari6303 3 года назад
Simple math to find length of point from origin. Suppose point p have (x,y) coordinate Then it's length = [ (x-0)^2 + (y-0)^2]^1/2 = (x^2+y^2)^1/2
@zakaryasidelazara8985
@zakaryasidelazara8985 4 года назад
why when you write after "def" it is purple and it's not in my pycharm?? what's mean?? thanks
@javiercaleragarcia1611
@javiercaleragarcia1611 4 года назад
Make sure you write double underscore, '_' '_' there are two not one.
@alfredmusiimentamarvin7823
@alfredmusiimentamarvin7823 4 года назад
i know i'm late but why did you add the plus(+) signs in the def__str__(self): return '('+ str(self.x) +', ' +str(self.y) + ')'
@alvilbalbuena289
@alvilbalbuena289 4 года назад
Because they are strings and you want to combine them together. Same way that when you typed in 'te'+'st' you will have 'test' as a result
@olaseni92
@olaseni92 4 года назад
@@alvilbalbuena289I am new to python but, why can't you just leave the return statement like this ---> return str(self.x) str(self.y)
@durianjaykin3576
@durianjaykin3576 5 лет назад
hey there, nice tutorial. Tried overloading __len__, just one issue, got a type error as 'float' object cannot be interpreted as integer, how would one go about fixing it so using len makes it able to output floats
@daivikbhatia5041
@daivikbhatia5041 5 лет назад
got the same problem. did you find any solution?
@rrl9786
@rrl9786 5 лет назад
@@daivikbhatia5041 I found the solution- see my comment to the main video.
@sourabhbarua3761
@sourabhbarua3761 4 года назад
While printing len(p1), I'm getting the error: TypeError: 'float' object cannot be interpreted as an integer How can I fix this?
@mahannk
@mahannk 4 года назад
def __len__(self): import math return int(math.sqrt(self.x**2 + self.y**2))
@rojadsorum9515
@rojadsorum9515 4 года назад
Is there any other series that explains this
@rojadsorum9515
@rojadsorum9515 4 года назад
There is another channel telusko that explains this
@KunalKumar-pc4vg
@KunalKumar-pc4vg 4 года назад
the method is help()
@nabeelest
@nabeelest 3 года назад
I don't understand why he used p.x in there?!
@Hassan.Wahba.97
@Hassan.Wahba.97 3 года назад
that's overriding not overloading! overloading is to have two methods with the same name but different params
@olaseni92
@olaseni92 4 года назад
Why are the plus (+) signs needed for this line of code def__str__(self): return '('+ str(self.x) +', ' +str(self.y) + ')'
@olaseni92
@olaseni92 4 года назад
Why does this not work def __str__(self): return str(self.x) str(self.y)
@Heck-ed6sr
@Heck-ed6sr 4 года назад
I'm pretty new myself but I think it's string concatenation, to link in a series the strings he wants as output
@Heck-ed6sr
@Heck-ed6sr 4 года назад
@@olaseni92 does it work if you use def __str__(self): return str(self.x) + str(self.y)
@olaseni92
@olaseni92 4 года назад
@@Heck-ed6sr Why do you need the plus sign? Why can't I return two strings?
@Heck-ed6sr
@Heck-ed6sr 4 года назад
@@olaseni92 it is possible for a single method/function to return 2 values. If you want to, place a comma between the 2 values (e.g. return str(self.x) , str(self.y) ) , however, the return value would be a 2-tuple and not a string. The __str__ method has to yield a str value and thus would not work when calling the object directly (e.g. a=point(2,3); print(a) ). However it could still work when using the method directly (e.g. a=point(2,3); print(a.__str__()) ) Also in my previous reply, I think using: return str(self.x) + ',' + str(self.y) would be more accurate as the comma between the 2 other strings helps to represent the data better. My apologies
@perceusdeniz1789
@perceusdeniz1789 Год назад
why ıs p5 = 9
@aaaaa12394
@aaaaa12394 3 года назад
6:48
@goggins6121
@goggins6121 4 года назад
im too dumb for this
@srali7609
@srali7609 4 года назад
this video i got really confused
@madhubathula4811
@madhubathula4811 3 года назад
does anyone see derek banas channel
@madhubathula4811
@madhubathula4811 3 года назад
Comment yes if you do
@FranzFakler
@FranzFakler 9 месяцев назад
Why do You always take this awful black theme ? You higlight Code wirtten red with green it completely disappears. A red dot You cannot see
@Edward_Nguyen
@Edward_Nguyen 4 года назад
hello, I have a question that why we need self.coords = (self.x, self.y). Please help me. Thank you so much
@usamatahir7091
@usamatahir7091 4 года назад
This is just if you want to print the coordinates of a point. e.g. if you do : >>> print( p1.coords) it will print the following output: (3, 4 )
@serious6037
@serious6037 3 года назад
you have wasted 13 minutes by explaining something that could be explained with 0 confusion in 1 minute.
@apoorvpathak5378
@apoorvpathak5378 3 года назад
This one is fucking hard to understand
@arshamsharifnia5474
@arshamsharifnia5474 4 года назад
thanks
Далее
A Monster is Chasing Me! 😭
00:19
Просмотров 1,2 млн
If __name__ == "__main__" for Python Developers
8:47
Просмотров 410 тыс.
25 nooby Python habits you need to ditch
9:12
Просмотров 1,8 млн
Learn Python OOP in under 20 Minutes
18:32
Просмотров 86 тыс.
This Is Why Python Data Classes Are Awesome
22:19
Просмотров 812 тыс.
Pydantic Tutorial • Solving Python's Biggest Problem
11:07
Python Decorators in 15 Minutes
15:14
Просмотров 448 тыс.