0

Why does python has so many magic methods if any magic method could be defined to do anything?

11th May 2020, 9:52 AM
Mons Joseph
Mons Joseph - avatar
2 Answers
+ 1
You can always use the tools you have to do damage. It's your responsibility as a programmer that you don't. Basically, 'magic method' is just a fancy name for operator overload - or maybe builtin syntax overload or something like that. (Whatever you call it, it's a mouthful. ;-)) You don't have to use these tools for the most part, but you can whenever you think it makes sense. Let's say, you have a class LegoPiece, and you want to create behavior making them connect. You could define a method 'add', or 'connect' or whatever. Then you'd have to write something like: piece3 = piece1.connect(piece2) You *could* also define the magic method __add__ for it, which is overloading the plus operator. That way you can write: piece3 = piece1+piece2
11th May 2020, 10:03 AM
HonFu
HonFu - avatar