+ 7
Magic methods overwrite in Python
Hello, As I understand from OOP course, statement 2+3 is equal to (2).__add__(3). So when we use arithmetic operators, magic methods work under the hood. But why if I try to change or overwrite the magic methods? For example: def __add__(var): print(“changed”) It doesn’t affect the statement 2+3. It still prints 5. Does it mean that magic methods can’t be overwritten outside of the classes? With other built in function it is possible but not with the magic ones. Appreciate your detailed replies!
7 odpowiedzi
+ 6
How operators behave in context of your custom classes, can be defined inside your classes. It is a bit more tricky though, because the left and right side of the operator may have different types. For example in Python you can multiply a string with an integer number, but you cannot add a number to a string. Also there is a __radd__ magic method which means the custom object in which you define this, is on the right side of an addition. Normally addition of numbers is commutative (meaning the order of operands doesn't matter) but in case of certain types of objects, this could be different or even invalid, for example you cannot just multiply matrices in the wrong order if their shapes are not compatible.
One example for magic method override:
https://code.sololearn.com/c53bgDF7Zwi6/?ref=app
You could also make a subclass of int and override some magic methods there. Cannot directly modify how ints are added.
More read: https://realpython.com/operator-function-overloading/
+ 5
Operator overload is only possible to implement for your own custom classes, not for the built-in data types.
I am not sure what you mean by "outside".
+ 1
I think you already hinted into the correct direction with "can't be overwritten outside of classes"
You can try this:
- find out the class of 2: `type(2)`
- let's say the type is Integer
- redefine Integer.__add__()
+ 1
Tibor Santa Thank you a lot for explanation and the website.
I somehow understood how the operator overloading works inside classes but still don’t get how it behaves outside them. As I roughly understand from your explanation it is almost impossible or difficult to implement.
+ 1
Tibor Santa, Thank you a lot! After some research I got the main idea.
0
Ruslan Guliyev i thought that
`def int.__add__()` would be how to redefine the `__add__` method of `int` class, but it isn't. Anyways, where can I find info about magic methods? AI couldn't find it in the python docs https://docs.python.org/3/library/stdtypes.html#numeric-types-int-float-complex
- 1
zs11, thanks for your answer!
Could you please explain more or give example of what you mean by the last line, integer.__add__()?
I’ve tried it but it gives an error.