Dunder methods in Python not only helps in operator overloading, but it gives the power to instantiate a class however we want (talking about new method).
In my opinion, most important βDunderβ or βMagicβ methods that everyone should consider while building a class are:
β new
β repr
β getattr and setattr
β iter and next
β enter and exit
What are some of your most commonly used dunder methods that you consider while designing a class ?
Top comments (2)
It all depends on the class, which should always be designed around its data. Think about the qualities of that data:
__str__
and__repr__
).__iter__
and__next__
).__eq__
,__lt__
,__le__
).__add__
,__mul__
, and similar math operators).__hash__
,__getattr__
and__setattr__
to make effectively immutable, also make comparable).__enter__
and__exit__
)__getdata__
and__setdata__
)The list goes on. but you get the idea.
Right, it depends on the use case, and fortunately or unfortunately (don't know π ) but I have used these the most.
Thanks for such an insightful information. I will make sure to ask the right questions πβπ»