Dunder Methods
- Ref https://holycoders.com/python-dunder-special-methods/
- See the end of page for example
Dunder | Description |
---|---|
__new__(self) |
return a new object (an instance of that class). It is called before init method. Know More |
__init__(self) |
is called when the object is initialized. It is the constructor of a class. |
__del__(self) |
for del() function. Called when the object is to be destroyed. Can be used to commit unsaved data or close connections. |
__repr__(self) |
for repr() function. It returns a string to print the object. Intended for developers to debug. Must be implemented in any class. |
__str__(self) |
for str() function. Return a string to print the object. Intended for users to see a pretty and useful output. If not implemented, repr will be used as a fallback. |
__bytes__(self) |
for bytes() function. Return a byte object which is the byte string representation of the object. |
__format__(self) |
for format() function. Evaluate formatted string literals like % for percentage format and ‘b’ for binary. |
__lt__(self, anotherObj) |
for < operator. |
__le__(self, anotherObj) |
for <= operator. |
__eq__(self, anotherObj) |
for == operator. |
__ne__(self, anotherObj) |
for != operator. |
__gt__(self, anotherObj) |
for > operator. |
__ge__(self, anotherObj) |
for >= operator. |
__hash__(self) |
for hash(obj) , it should return an integer. obj1 == obj2 should mean hash(obj1) == hash(obj2) |
__bool__(self) |
for bool(obj) , if not defined, then __len__ is called and obj is defined as true if __len__ returns non 0 |
Arithematic¶
Dunder | Description |
---|---|
__add__(self, y) __sub__(self, y) __mul__(self, y) |
for +, -, * operation on object. |
__and__(self, y) __or__(self, y) __xor__(self, y) __neg__(self) |
obj & y obj | y obj ^ y negation of object |
__matmul__(self, y) |
for @ operator (numpy matrix multiplication). |
__truediv__(self, y) |
for simple / division operation on object. |
__floordiv__(self, y) |
for // floor division operation on object. |
__mod__(self, y) |
obj % anotherobj |
__pow__(self, y) |
obj ** y |
__lshift__(self, y) |
obj << y |
__abs__(self) |
make support for abs() function. Return absolute value. |
__round__(self, nDigits) |
for round() function. Round off float type to 2 digits and return it. |
__int__(self) __float__(self) __complex__(self) |
support for int(), float() and complex() methods on object |
__trunc__(self) |
for trunc() function of math module. Returns the real value of the object. |
__ceil__(self) __floor__(self) |
for ceil() and floor() function on object. |
Containor type¶
Dunder | Description |
---|---|
__len__(self) |
for len() function. Returns the total number in any container. |
__getitem__(self, key) |
to support indexing. LIke container[index] calls container.__getitem(key)explicitly. |
__setitem__(self, key, value) |
makes item mutable (items can be changed by index), like container[index] = otherElement. |
__delitem__(self, key) |
for del() function. Delete the value at the index key. |
__iter__(self) |
returns an iterator when required that iterates all values in the container. |
__dir__(self) |
A sequence must be returned |
__contains__(self, x) |
Should returns the output of x in obj |
class Account:
# def __new__(self):
# print("__new__ called A new account is Created.")
def __init__(self, name, balance = 0):
self.name = name
self._balance = balance
print("(__init__) Account Created with {} balance".format(self._balance))
def getBalance(self):
return self._balance
def __repr__(self):
return "(__repr__) Account({0}, {1})".format(self.name, self._balance)
def __str__(self):
return "(__str__) Account Name = {0}, Account Balance = {1}".format(self.name, self._balance)
def __lt__(self, otherObj):
try:
return self._balance<otherObj.getBalance()
except:
return "Cannot Be compared."
def __del__(self):
self._balance = 0
print("(__del__) Account Deleted")
digvijay_ac = Account("Digvijay Singh", 500)
saket_ac = Account("Digvijay Singh", 700)
print(str(digvijay_ac))
print(repr(digvijay_ac))
print(digvijay_ac<saket_ac)
OP:¶
(__init__) Account Created with 500 balance
(__init__) Account Created with 700 balance
(__str__) Account Name = Digvijay Singh, Account Balance = 500
(__repr__) Account(Digvijay Singh, 500)
True
(__del__) Account Deleted
(__del__) Account Deleted