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. - 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.