Python Dunder Method

In Python, built-in functions and operators work by inspecting objects for special behavior-defining methods. These methods are known as dunder methods because they are pref- and suffixed with two underscores.


__Abs__


__Add__


__AEnter__

See the specification for context managers.


__AExit__

See the specification for context managers.


__And__


__Bool__


__Ceil__


__Class__


__Copy__

See here for details.


__DeepCopy__

See here for details.


__Del__


__DelAttr__


__DelItem__


__Dir__


__DivMod__


__Doc__


__Enter__

See the specification for context managers.


__Eq__


__Exit__

See the specification for context managers.


__Float__


__Floor__


__FloorDiv__


__Format__


__Ge__


__GetAttr__

When attempting to access an object's attributes, conventionally an AttributeError will be raised if the lookup fails. To customize this behavior, a custom __getattr__() implementation can be set. This hooks into all attribute lookups that fail.

class Codes(object):
    def __getattr__(self, attr: str) -> str:
        return attr


__GetAttribute__

To override the attribute lookup process entirely for an object, a custom __getattribute__() implementation can be set.

class ObfuscatedData(object):
    def __getattribute__(self, attr: str) -> str:
        return 'REDACTED'


__GetItem__


__GetNewArgs__


__Gt__


__Hash__


__Index__


__Init__


__Init_Subclass__


__Int__


__Invert__


__Le__


__Len__


__LShift__


__Lt__


__Mod__


__Mul__


__Ne__


__Neg__


__New__

The __new__() method is called immediately when a class instance is created, even before __init__().

class Employee(object):
    def __new__(cls):
        print("INFO: creating new employee")
        return object.__new__(cls)

The return type is best annotated as typing.Self. See here for more details.


__Or__


__Pos__


__Pow__


__RAdd__

The reflected __add__() method.


__RAnd__

The reflected __and__() method.


__RDivMod__

The reflected __divmod__() method.


__Reduce__


__Reduce_Ex__


__Repr__


__RFloorDiv__

The reflected __floordiv__() method.


__RLShift__

The reflected __lshift__() method.


__RMod__

The reflected __mod__() method.


__RMul__

The reflected __mul__() method.


__ROr__

The reflected __or__() method.


__Round__


__RPow__

The reflected __pow__() method.


__RRShift__

The reflected __rshift__() method.


__RShift__


__RSub__

The reflected __sub__() method.


__RTrueDiv__

The reflected __truediv__() method.


__RXor__

The reflected __xor__() method.


__SetItem__


__SizeOf__


__Str__


__Sub__


__SubclassHook__


__TrueDiv__


__Trunc__


__Xor__


CategoryRicottone

Python/DunderMethod (last edited 2023-04-11 17:33:30 by DominicRicottone)