I know that classes can implement various special methods, such as __iter__, __setitem__, __len__, __setattr__, and many others. But when should I use them? Can anyone describe typical scenarios when I would want to implement them and they would simplify programming in Python?
Thanks, Boda Cydo.
I think you basically answered your question.
Become familiar with the special methods. If you find that using one will make your program simpler, use it. If you don’t understand what one is for, or feel like it is a more complex solution – you have answered the question. Don’t use it.
The typical scenarios are :
Overriding operators
Catching access to attributes that don’t exist and dealing with that access (
__getattr__)Manipulating class and instance creation (
__init__,__slots__,__new__)Customizing string representations (
__str__and__repr__)allowing callability (
__call__)Hooking into convenient/well-used builtin syntax (
__getitem__,__len__, etc…)These are mostly covered at https://docs.python.org/reference/datamodel.html#specialnames and http://docs.python.org/reference/datamodel.html#special-method-names