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.
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).
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.
For further actions, you may consider blocking this person and/or reporting abuse
We're a place where coders share, stay up-to-date and grow their careers.
Good stuff, 2 quick points I'd like to make:
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.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).
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.