+ 1
How does a function "implement" a magic method?
In the example, it said x+y would not translate to x.__add__(y) if x does not implement __add__. And will proceed to call y.__radd__(x) But what exactly is implementing? How does x implement or not implement __add__? And what differences are implied when y.__radd__(x) is called instead of x.__add__(y)?
5 ответов
+ 5
It also took me a while to get the whole OOP stuff and I had to postpone it, leaving the tutorial unfinished.
After a while of writing code using only regular functions, it suddenly clicked, it came basically out of nowhere.
I suppose your brain needs to get ready, while you constantly prepare the soil, doing simpler stuff as long as needed.
+ 3
When you write a class, you can define what happens with a specific operator; for this purpose, Python has specific reserved method names.
class C:
def __add__(self, other):
print('No, we don't do '
'adding in this place!')
So when later you try to use + with two C-instances, you won't get an error - but the strange line above is printed.
You could define any meaningful or nonsensical meaning.
Normally you would use + in your code, because it's short and intuitive; but whenever a type has __add__ defined, you can technically also write it like you showed above.
The built-in type 'int' has implemented __add__, because obviously you want to be able to add numbers.
So int.__add__(5, 7) or 5.__add__(7) are peculiar variations of just writing 5+7.
The built-in type str also has its own __add__-implementation:
When you add strings, they get tied up: 'a'+'b' == 'ab'
Again, you could also write it the complicated way.
+ 3
Check out the code below. It implements a new, "better" String class which supports string subtracting (in a somewhat special way ;)
Normally, the classic 'str' class does not support the minus sign and would raise a TypeError exception.
But since I created a class inheriting from string and implementing the subtraction operation, by defining the respective magic method, both Strings get the operation done and return the result I wanted.
https://code.sololearn.com/co9272TlZKBU/?ref=app
+ 1
Kuba Siekierzyński, nice idea for a demonstration! :-)
0
I understand some of what you mentioned but Im still confused in general, honestly. I will set this aside for now, and come back some other time. Maybe after playing some more with magic methods I might get to answer my concerns. Thank you nevertheless