:::: MENU ::::

Python3 dunder methods summary with examples

Below you can find a summary 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

MethodInvokedNotesDocumentation
object.__new__(cls[, ...])instance = MyClass()Called to create a new instance of class cls.Python 3 Documentation
MyClass.__init__(self[, ...])instance = MyClass()Called after the instance has been created (by __new__()), but before it is returned to the caller. Python 3 Documentation
instance.__del__(self)del instanceCalled when the instance is about to be destroyed.Python 3 Documentation
instance.__repr__(self)repr(instance)Called by the repr() built-in function to compute the “official” string representation of an object. Python 3 Documentation
instance.__str__(self)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
instance.__bytes__(self)bytes(instance)Called by bytes to compute a byte-string representation of an object. Python 3 Documentation
instance.__format__(selfformat_spec)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 < yPython 3 Documentation
x.__le__(y)x <= yPython 3 Documentation
x.__eq__(y)x == yPython 3 Documentation
x.__ne__(y)x != yPython 3 Documentation
x.__gt__(y)x > yPython 3 Documentation
x.__ge__(y)x >= yPython 3 Documentation
instance.__hash__(self)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__(self)bool(instance)Called to implement truth value testing and the built-in operation bool(); should return False or True. Python 3 Documentation
Summary of basic Python dunder methods.

Customizing attribute access

MethodInvokedNotesDocumentation
instance.__getattr__(selfname)value = instance.nameCalled when the default attribute access fails with an AttributeError. Meaning there is no name attribute in that object. Python 3 Documentation
instance.__getattribute__(selfname)value = instance.nameCalled unconditionally to implement attribute accesses for instances of the class. Invoked before looking at the actual attributes within the object. Python 3 Documentation
instance.__setattr__(selfnamevalue)instance.name = valueCalled when an attribute assignment is attempted.Python 3 Documentation
instance.__delattr__(selfname)del instance.nameLike __setattr__() but for attribute deletion instead of assignment. Python 3 Documentation
instance.__dir__(self)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
Summary of attribute access dunder methods.

Container methods

MethodInvokedNotesDocumentation
instance.__len__(self)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.__getitem__(selfkey)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.__setitem__(selfkeyvalue)instance[key] = valueCalled to implement assignment to self[key].Python 3 Documentation
instance.__delitem__(selfkey)del instance[key]Called to implement deletion of self[key].Python 3 Documentation
instance.__missing__(selfkey)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__(self)iter(instance)This method is called when an iterator is required for a container.Python 3 Documentation
instance.__reversed__(self)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__(selfitem)item in instanceCalled 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
Summary of container dunder methods.

Numeric operations (Python 3 Documentation)

MethodOperation
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
Summary of numeric dunder methods.

Context managers

MethodInvokedNotesDocumentation
instance.__enter__(self)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.__exit__(selfexc_typeexc_valuetraceback)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
Summary of context manager dunder methods.

Callable objects

MethodInvokedNotesDocumentation
instance.__call__(self[, args...])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
Summary of callable objects dunder methods.

Descriptors

MethodInvokedNotesDocumentation
attr.__get__(selfinstanceowner=None)value = instance.attrCalled 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
attr.__set__(selfinstancevalue)instance.attr = valueCalled to set the attribute on an instance instance of the owner class to a new value, value.
Python 3 Documentation
attr.__delete__(selfinstance)del instance.attrCalled to delete the attribute on an instance instance of the owner class.Python 3 Documentation
attr.__set_name__(selfownername)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
Summary of descriptors dunder methods.