Where is a complete list of the special double-underscore/dunder methods that can be used in classes? (e.g., __init__, __new__, __len__, __add__)
Where is a complete list of the special double-underscore/dunder methods that can be used in classes? (e.g., __init__, __new__, __len__, __add__)
Following on from @Justin's answer, he included 95 items, here are the dunder methods I could infer: # 105 on 2.7 and 108 on 3.10:
from functools import partial
from itertools import chain
# From https://github.com/Suor/funcy/blob/0ee7ae8/funcy/funcs.py#L34-L36
def rpartial(func, *args):
"""Partially applies last arguments."""
return lambda *a: func(*(a + args))
dunders = tuple(filter(rpartial(str.startswith, "__"),
frozenset(chain.from_iterable((
# https://docs.python.org/3/library/stdtypes.html
chain.from_iterable(map(dir, (int, float, complex,
list, tuple, range,
str, bytes,
# 2.7: unicode,
bytearray, memoryview,
set, frozenset, dict,
type, None, Ellipsis,
NotImplemented, object)
)),
# https://docs.python.org/3/library/functions.html#dir
dir(),
# https://docs.python.org/3/library/stdtypes.html#special-attributes
("__dict__", "__class__", "__bases__", "__name__",
"__qualname__", "__mro__", "__subclasses__",
# https://docs.python.org/3/reference/datamodel.html#slots
"__slots__")
)))))
Output on 3.10:
('__abs__',
'__abstractmethods__',
'__add__',
'__alloc__',
'__and__',
'__annotations__',
'__base__',
'__bases__',
'__basicsize__',
'__bool__',
'__builtins__',
'__cached__',
'__call__',
'__ceil__',
'__class__',
'__class_getitem__',
'__contains__',
'__delattr__',
'__delitem__',
'__dict__',
'__dictoffset__',
'__dir__',
'__divmod__',
'__doc__',
'__enter__',
'__eq__',
'__exit__',
'__file__',
'__flags__',
'__float__',
'__floor__',
'__floordiv__',
'__format__',
'__ge__',
'__getattribute__',
'__getformat__',
'__getitem__',
'__getnewargs__',
'__gt__',
'__hash__',
'__iadd__',
'__iand__',
'__imul__',
'__index__',
'__init__',
'__init_subclass__',
'__instancecheck__',
'__int__',
'__invert__',
'__ior__',
'__isub__',
'__itemsize__',
'__iter__',
'__ixor__',
'__le__',
'__len__',
'__loader__',
'__lshift__',
'__lt__',
'__mod__',
'__module__',
'__mro__',
'__mul__',
'__name__',
'__ne__',
'__neg__',
'__new__',
'__or__',
'__package__',
'__pos__',
'__pow__',
'__prepare__',
'__qualname__',
'__radd__',
'__rand__',
'__rdivmod__',
'__reduce__',
'__reduce_ex__',
'__repr__',
'__reversed__',
'__rfloordiv__',
'__rlshift__',
'__rmod__',
'__rmul__',
'__ror__',
'__round__',
'__rpow__',
'__rrshift__',
'__rshift__',
'__rsub__',
'__rtruediv__',
'__rxor__',
'__set_format__',
'__setattr__',
'__setitem__',
'__sizeof__',
'__slots__',
'__spec__',
'__str__',
'__sub__',
'__subclasscheck__',
'__subclasses__',
'__subclasshook__',
'__text_signature__',
'__truediv__',
'__trunc__',
'__weakrefoffset__',
'__xor__')