Dunder Functions
Dunder word is taken by composing “Double” and “Underscore”. So, dunder functions are functions that start and end with double underscores. In python, interpreter treats them specially and these functions are not used directly. However, in some cases we may require to use these functions.
These functions enable us to make user defined data structures compatible with basic data types, apply arithmetic operations on instances, etc. For instance, we can make an instance of class Person
addition with another instance of same class (or different class).
class Person():
def __init__(self, age):
self.age = age
def __add__(self, another):
return Person(self.age + another.age)
a = Person(2)
b = Person(2)
print((a + b).age)
4
There are several dunder functions available.
Dunder function | Usage |
---|---|
__setitem__ and __getitem__ | Handling indexing |
__add__ , __sub__ , __div__ etc | Arithmetic operations |
__init__ | Initialise object |
__lt__ , __gt__ , __le__ etc | Relational operators. |