+ 2

Magic methods in Python

Hi, cam somebody please explain me what a magic method is, I did the magic method in Pyrhon core, and repeated lots of time, but still. I don't understand anything about the code that Sololearn have used. Can somebody please explain me what magic method are and can somebody please give me an example of a magic method? Thank you

3rd Aug 2022, 9:37 PM
Danish Zubair
Danish Zubair - avatar
2 Respostas
+ 5
Hi, Danish Zubair ! In Python, magic methods are methods whose name begin and end with two underscores, like __ init__(), __add__(), __len__() or __repr__(). If you run help(obj) for an object, you can see the magic methods for that object, like help(int) or help(str). When you run an object method (or built in function) in a program, for example for a string, it calls its corresponding magic method interly. This happen for example when you call len(“abc”) or len([1, 2, 3]). len() looks same for the both objects, but run different methods connected to its objects data type: So “abc”.__len__() and [1, 2, 3].__len__() are two different methods. So when you create your own classes in Python, you can change the behavior for those methods or functions, for a special data type. Take len() as an example. Let len(“abc”) work as usual, but when you use len() on a object for a class you created, somthing very special could happen; what - is up to you: It’s kind of magic.
3rd Aug 2022, 11:59 PM
Per Bratthammar
Per Bratthammar - avatar
+ 1
Per Bratthammar thats cool. So theyre magic because you can change these core functions as magic method format first? Very cool.
4th Aug 2022, 12:05 AM
ÏÒŻà«šĆ“dԌ૚ ×
ÏÒŻà«šĆ“dԌ૚ × - avatar