Im sorry for asking this bit what are these magic methods for? (except __init__) | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

Im sorry for asking this bit what are these magic methods for? (except __init__)

13th Jul 2016, 4:57 AM
Fabian Dürr
Fabian Dürr - avatar
3 Answers
+ 4
they are useful to make operator overloading for example. A example let say you have two objects from a class Product, let's call then Pen and Pencil. these two objects have an attribute called price and you want to sum the price of them. so you could create a method sum with magic method __add__ to calculate Pen.price + Pencil.price. After you have done this method , you will be able to compute price of whatever object from class Product you want. I hope I was clear enough :)
14th Jul 2016, 12:45 PM
Daniel Costa
Daniel Costa - avatar
0
they are implicitly called in certain situations like using operators, type conversions, etc. you can read more here http://www.rafekettler.com/magicmethods.html .
13th Jul 2016, 11:32 AM
RedAnt
RedAnt - avatar
0
thank you
14th Jul 2016, 6:32 PM
Fabian Dürr
Fabian Dürr - avatar