Why do you need magic methods? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

Why do you need magic methods?

Instead of '__init__' why wouldn't 'init' work?

7th Feb 2017, 5:18 PM
Paul Silvestri
Paul Silvestri - avatar
1 Answer
+ 2
I guess you're talking about Python. It's about methods that you don't call by their explicit name, but with other operands instead. Take __init__, for example. You needn't call it like obj.__init__() explicitly, but it's called every time you instantiate an object from a class. Another examples are __add__, __mul__, and so on. These allow you to call operations on objects directly by writing obj1+obj2 or obj1*obj2, respectively. This improves the readability of your code, I guess. For some examples, take a look at my code in https://code.sololearn.com/czR5J2MP74iB/?ref=app For a thorough list of all magic methods, take a look at: http://www.diveintopython3.net/special-method-names.html
7th Feb 2017, 5:38 PM
Álvaro