+ 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
2 ответов
+ 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.
+ 1
Per Bratthammar thats cool. So theyre magic because you can change these core functions as magic method format first? Very cool.