Dunder methods (double-underscore methods like __str__, __len__) should be implemented in your Python classes but not called directly. Instead of calling obj.__str__(), use str(obj). Python's built-in functions and operators provide the proper high-level interface to these low-level implementation details. Direct dunder method calls can fail in cases where the high-level operations would succeed, such as with type coercion between integers and floats.

6m read timeFrom pythonmorsels.com
Post cover image
Table of contents
What is a dunder method?Define dunder methods on your classesDon't call dunder methods on your objectsWhy not call dunder methods?Sometimes you need to call dunder methodsAvoid calling dunder methods, but do define them

Sort: