Are magic methods used very often? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 2

Are magic methods used very often?

I can’t seem to find any use for magic methods as a beginner. Does anyone (beginner, advanced, etc.) use them often?

17th Dec 2019, 9:57 PM
꧁༺ Jenspi ༻꧂
꧁༺ Jenspi ༻꧂ - avatar
2 Answers
+ 1
class Person: def __init__(self, firseName, lastName): self.fname = firseName.title() self.lname = lastName.title() def __str__(self): ## < this magic method called by the print function. return self.fname + " " + self.lname def __len__(self): ## < this magic method is called by the len function return len(self.fname + self.lname) me = Person("angus", "young") print(me) print(len(me))
17th Dec 2019, 10:23 PM
rodwynnejones
rodwynnejones - avatar
+ 1
One use for them is defining custom operations between objects of your class. Then you can use shorthands when manipulating the objects. There are lots of magic methods that may be useful depending on what your class represents. Play around with making classes and see which ones would be useful in your situation. An example of when I've used them is when I made a class representing 3D vectors. I used the __add__ and __sub__ magic methods to represent vector addition and subtraction in a way that is more intuitive (lets me use the + and - symbols between vectors). I also used the __repr__ magic method for string representation so that I would be able to print the vector objects to the console to actually see the results of calculations. Here's the code so you can have a look: https://code.sololearn.com/ci2jGI4TAfvo/?ref=app
18th Dec 2019, 7:48 PM
Njeri
Njeri - avatar