0

Please , help me to understand the reason of using the magic methods in class ( PYTHON)???

I need your help.

31st Oct 2019, 3:53 PM
Влад Гребенюе
Влад Гребенюе - avatar
6 ответов
+ 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
31st Oct 2019, 6:23 PM
Qasem
+ 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]
31st Oct 2019, 4:15 PM
Asman-H
Asman-H - avatar
+ 1
I can not realise this explanation. Could somebody tell me more understandable???
31st Oct 2019, 4:18 PM
Влад Гребенюе
Влад Гребенюе - avatar
+ 1
It is for operator overloading.Suppose you want to use +,-,*,/,etc in a different way then you can redefine them.
31st Oct 2019, 4:43 PM
Jayesh Mishra
Jayesh Mishra - avatar
+ 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
31st Oct 2019, 5:04 PM
Tibor Santa
Tibor Santa - avatar
0
Here’s an example with addition and subtraction. https://code.sololearn.com/c54jn2y004wp/?ref=app
1st Nov 2019, 8:12 PM
Rora