Operator overloading - Intermediate Python Programming p.19 | Tokyo
Information | History | View | Sightseeing | Video
Welcome to part 19 of the intermediate Python programming tutorial series. In this tutorial, we are going to introduce the "special" or "magic" methods of Python, and, with that, talk about operator overloading, which is where we can define new ways for Python to handle operators like "+" in our example. https://pythonprogramming.net https://twitter.com/sentdex https://www.facebook.com/pythonprogramming.net/ https://plus.google.com/+sentdex
Comments
-
Blobjects ROFL
-
awesome video, very useful and clear!
-
This is like watching a Bob Ross video. Thanks!
-
and as always thank you for changing my life
-
Basically, without resorting to C, one can create your own datatypes using operator overloading. I've done this myself when I had a project that needed ordered-named-lists (like a dictionary, but the keys need not be unique.) Wish your videos had been around when I was learning how. Some extra info for others: the example he used is good for blue_blob + red_blob. But red_blob + blue_blob will fail; that is because the _add_ operator is referenced by the first object, with the second object as the parameter. One could need to define _add_ in the RedBlob class for _add to become "commutative" (i.e. getting it to work in both directions.) Or, one could add a default _add_ to the Blob parent class; then overload again for unique properties based on color. ...it is easy to go down some twisty rabbit holes with these techniques... :)
-
winds me up all that code means nothing if you don't show the result of it! it looks like all that code just makes lil squares hmmmm strange.
-
like C++
Two things I find need to be mentioned. First of all: you can add / subtract and so on different objects. One thing that you need to keep in mind though is that a + b is basically a.__add__(b) the addition is not commutative.
The other thing is that like you showed in the video the addition doesn't have any return value so for example bloby = red_blob + blue_blob. Then bloby is None. If you want to have a return value, create a new object.