DEV Community

Siddharth Chandra
Siddharth Chandra

Posted on

Python Dunder Magic 🐍

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)

Collapse
 
codemouse92 profile image
Jason C. McDonald • Edited

It all depends on the class, which should always be designed around its data. Think about the qualities of that data:

  • Should it be string-representable? (__str__ and __repr__).
  • Should it be iterable? (__iter__ and __next__).
  • Should it be comparable? (__eq__, __lt__, __le__).
  • Should it be numeric? (__add__, __mul__, and similar math operators).
  • Should it be hashable? (__hash__, __getattr__ and __setattr__ to make effectively immutable, also make comparable).
  • Should it be a context manager? That is, does it need to be opened and/or closed, like a stream? (__enter__ and __exit__)
  • Should it be picklable for use with multiprocessing? (__getdata__ and __setdata__)

The list goes on. but you get the idea.

Collapse
 
siddharth2016 profile image
Siddharth Chandra

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 😁✌🏻