Unsorted Random Notes
Method calls and interpreters
__methods__are only meant to be called by Python interpreters, not by you directly.- If you need to call a
__method__, it’s usually better to call the related built-in function (e.g.len,iter,str, etc.) rather than__len__()directly. - Sometimes, the
__method__andmethod()built-in produces different results. For example,list.sort()sorts a list in place and returnsNoneindicating that no new object was created, whilesorted(list)creates a new list and returns it. Theshuffles()built-in has the same behaviour assorted(). - Built-in types are often optimised for performance - take advantage of them when you can.
__repr__and__str__- if you implement one, pick__repr__. It represents the string representation of the object, and you should be able to recreate the object from__repr__’s output. It’s also the fallback for__str__.
Python classes and inheritance
- Python doesn’t require concrete classes to actually inherit from ABCs. E.g. any class that implements
__len__satisfies the “Sized” ABC. Some call this an “interface” in other programming languages. - In Python, “special cases aren’t special enough to break rules.” Hence
__len__always works withlen(), even though the internals may be very different (e.g. optimised at C level or with special header properties). - By implementing special methods, your objects can behave like built-in types, enabling expressive “Pythonic” coding styles.