0
Please , help me to understand the reason of using the magic methods in class ( PYTHON)???
I need your help.
6 Answers
+ 1
When you want to change class default behaviors you can use magic methods.
For example suppose you want to define an object that when it's added to another similar object, their values will be multiplied.
obj1 + obj2 => (obj1.value * obj2.value)
You can change this behavior in a magic method inside of objects' class:
def __add__(self, other):
return self.value * other.value
+ 1
Hi!
Sorry, but I can't tell it in two words, it is big topic. Basically, you need them, when working with OOP.
But you can learn what is magic methods in Python course. In Python course, there is module, called OOP (Object-Orientated Programming). In this module, it is explained, what is magic methods, and how you work with them.
Consider that it will be difficult to understand magic methods, if you haven't finished all previous modules of Python course. I strongly recommend to start (if you didn't) learning Python course, from SoloLearn.
[EDITED]
+ 1
I can not realise this explanation. Could somebody tell me more understandable???
+ 1
It is for operator overloading.Suppose you want to use +,-,*,/,etc in a different way then you can redefine them.
+ 1
I have an example where I implemented the __eq__ magic method, which is used when you compare two instances of the same class. Maybe it helps you.
https://code.sololearn.com/cpml1yX5qqmD/?ref=app
0
Hereās an example with addition and subtraction.
https://code.sololearn.com/c54jn2y004wp/?ref=app