DEV Community 👩‍💻👨‍💻

Discussion on: How to write better Python classes using Magic Methods

vdedodev profile image
Vincent Dedo

Good stuff, 2 quick points I'd like to make:

  1. Make sure the behaviour of magic methods is unambiguous. People are more likely to read a docstring for add than __add__. I think I've misused magic methods once or twice and there's no explicit function call so it can be hard to track down.

  2. I know the point is to have an easy concept/example in your article, but this is basically a cut down timedelta from the datetime module. To newer python devs, don't re-invent the wheel (or timedelta/TimePeriod).

bikramjeetsingh profile image
Bikramjeet Singh Author

Thanks Vincent, both excellent points. Ideally, such magic methods are best used only in situations where it's immediately intuitive/apparent to the reader how the addition (or any other operation) would work. If the business logic behind the addition is more complex, it's probably worth it to write a fresh method instead.