Below you can find a list of Python dunder methods as well as when they are invoked. Those two pieces of information put together should give you a better overview when to use which. The post is inspired on those materials available online: Python 3 documentation, Python Dunder Methods by Fernando Souza, python-course.
Assume that we have a class called MyClass
.
Basic customization
Method | Invoked | Notes | Documentation |
---|---|---|---|
object. | instance = MyClass() | Called to create a new instance of class cls. | Python 3 Documentation |
MyClass. | instance = MyClass() | Called after the instance has been created (by __new__() ), but before it is returned to the caller. | Python 3 Documentation |
| del instance | Called when the instance is about to be destroyed. | Python 3 Documentation |
instance. | repr(instance) | Called by the repr() built-in function to compute the “official” string representation of an object. | Python 3 Documentation |
| str(instance) | Called by str(object) and the built-in functions format() and print() to compute the “informal” or nicely printable string representation of an object. | Python 3 Documentation |
| bytes(instance) | Called by bytes to compute a byte-string representation of an object. | Python 3 Documentation |
| format(instance, spec) | Called by the format() built-in function, and by extension, evaluation of formatted string literals and the str.format() method, to produce a “formatted” string representation of an object. | Python 3 Documentation |
x.__lt__(y) | x < y | Python 3 Documentation | |
x.__le__(y) | x <= y | Python 3 Documentation | |
x.__eq__(y) | x == y | Python 3 Documentation | |
x.__ne__(y) | x != y | Python 3 Documentation | |
x.__gt__(y) | x > y | Python 3 Documentation | |
x.__ge__(y) | x >= y | Python 3 Documentation | |
instance. | hash(instance) | If a class does not define an __eq__() method it should not define a __hash__() operation either; If it defines __eq__() but not __hash__() , its instances will not be usable as items in hashable collections. If a class defines mutable objects and implements an __eq__() method, it should not implement __hash__() , since the implementation of hashable collections requires that a key’s hash value is immutable (if the object’s hash value changes, it will be in the wrong hash bucket). | Python 3 Documentation |
instance. | bool(instance) | Called to implement truth value testing and the built-in operation bool() ; should return False or True . | Python 3 Documentation |
Customizing attribute access
Method | Invoked | Notes | Documentation |
---|---|---|---|
instance. | value = instance.name | Called when the default attribute access fails with an AttributeError . Meaning there is no name attribute in that object. | Python 3 Documentation |
instance. | value = instance.name | Called unconditionally to implement attribute accesses for instances of the class. Invoked before looking at the actual attributes within the object. | Python 3 Documentation |
instance. | instance.name = value | Called when an attribute assignment is attempted. | Python 3 Documentation |
instance. | del instance.name | Like __setattr__() but for attribute deletion instead of assignment. | Python 3 Documentation |
instance. | dir(instance) | A sequence must be returned with a list of valid attributes for that object. dir() converts the returned sequence to a list and sorts it. | Python 3 Documentation |
Container methods
Method | Invoked | Notes | Documentation |
---|---|---|---|
instance. | len(instance) | Called to implement the built-in function len() . Should return the length of the object, an integer >= 0. Also, an object that doesn’t define a __bool__() method and whose __len__() method returns zero is considered to be false in a Boolean context. | Python 3 Documentation |
instance. | value = instance[key] | Called to implement evaluation of self[key] . For sequence types, the accepted keys should be integers and slice objects. | Python 3 Documentation |
instance. | instance[key] = value | Called to implement assignment to self[key] . | Python 3 Documentation |
instance. | del instance[key] | Called to implement deletion of self[key] . | Python 3 Documentation |
instance. | value = instance[key] | Called by dict .__getitem__() to implement self[key] for dict subclasses when key is not in the dictionary. | Python 3 Documentation |
instance. | iter(instance) | This method is called when an iterator is required for a container. | Python 3 Documentation |
instance. | reversed(instance) | Called (if present) by the reversed() built-in to implement reverse iteration. It should return a new iterator object that iterates over all the objects in the container in reverse order. | Python 3 Documentation |
instance.__contains__(self, item) | item in instance | Called to implement membership test operators. Should return true if item is in self, false otherwise. For mapping objects, this should consider the keys of the mapping rather than the values or the key-item pairs. | Python 3 Documentation |
Numeric operations (Python 3 Documentation)
Method | Operation |
---|---|
x.__divmod__(self, y) | divmod(x, y) |
x.__rdivmod__(self, y) | divmod(y, x) |
x.__invert__(self) | ~x |
x.__index__(self) | operator.index(x) |
x.__ceil__(self) | ceil(x) |
x.__floor__(self) | floor(x) |
x.__pos__(self) | +x |
x.__neg__(self) | -x |
x.__complex__(self) | complex(x) |
x.__float__(self) | float(x) |
x.__int__(self) | int(x) |
x.__round__(self[, n]) | round(x) |
x.__trunc__(self) | trunc(x) |
x.__abs__(self) | abs(x) |
x.__add__(self, y) | x + y |
x.__sub__(self, y) | x - y |
x.__mul__(self, y) | x * y |
x.__pow__(self, y) | x ** y |
x.__truediv__(self, y) | x / y |
x.__floordiv__(self, y) | x // y |
x.__mod__(self, y) | x % y |
x.__and__(self, y) | x & y |
x.__or__(self, y) | x | y |
x.__xor__(self, y) | x ^ y |
x.__lshift__(self, y) | x << y |
x.__rshift__(self, y) | x >> y |
x.__matmul__(self, y) | x @ y |
x.__radd__(self, y) | y + x |
x.__rsub__(self, y) | y - x |
x.__rmul__(self, y) | y * x |
x.__rpow__(self, y) | y ** x |
x.__rtruediv__(self, y) | y / x |
x.__rfloordiv__(self, y) | y // x |
x.__rmod__(self, y) | y % x |
x.__rand__(self, y) | y & x |
x.__ror__(self, y) | y | x |
x.__rxor__(self, y) | y ^ x |
x.__rlshift__(self, y) | y << x |
x.__rrshift__(self, y) | y >> x |
x.__rmatmul__(self, y) | y @ x |
x.__iadd__(self, y) | x += y |
x.__isub__(self, y) | x -= y |
x.__imul__(self, y) | x *= y |
x.__ipow__(self, y) | x **= y |
x.__itruediv__(self, y) | x /= y |
x.__ifloordiv__(self, y) | x //= y |
x.__imod__(self, y) | x %= y |
x.__iand__(self, y) | x &= y |
x.__ior__(self, y) | x |= y |
x.__ixor__(self, y) | x ^= y |
x.__ilshift__(self, y) | x <<= y |
x.__irshift__(self, y) | x >>= y |
x.__imatmul__(self, y) | x @= y |
Context managers
Method | Invoked | Notes | Documentation |
---|---|---|---|
instance. | with instance as obj: | Enter the runtime context related to this object. The with statement will bind this method’s return value to the target(s) specified in the as clause of the statement, if any. | Python 3 Documentation |
instance. | with instance as obj: | Exit the runtime context related to this object. The parameters describe the exception that caused the context to be exited. If the context was exited without an exception, all three arguments will be None . | Python 3 Documentation |
Callable objects
Method | Invoked | Notes | Documentation |
---|---|---|---|
instance. | instance(args...) | Called when the instance is “called” as a function; if this method is defined, x(arg1, arg2, ...) roughly translates to type(x).__call__(x, arg1, ...) .3.3.7 | Python 3 Documentation |
Descriptors
Method | Invoked | Notes | Documentation |
---|---|---|---|
| value = instance.attr | Called to get the attribute of the owner class (class attribute access) or of an instance of that class (instance attribute access). The optional owner argument is the owner class, while instance is the instance that the attribute was accessed through, or None when the attribute is accessed through the owner. | Python 3 Documentation |
| instance.attr = value | Called to set the attribute on an instance instance of the owner class to a new value, value. | Python 3 Documentation |
| del instance.attr | Called to delete the attribute on an instance instance of the owner class. | Python 3 Documentation |
| class A: attr = Attr() calls attr.__set_name__(A, 'attr') | Automatically called at the time the owning class owner is created. The object has been assigned to name in that class. | Python 3 Documentation |