__GETITEM__ and __SETITEM__ in Python
These methods are used in assignment operations, unary comparison operations, binary comparison operations and binary operations. These are pre-defined methods that perform many operations on a class instance. Examples like __init__ (), __call__ (),__str__ () dunder methods were used. Dunder methods are both sides dual underscore (_) methods which are used to assess the behavior of built -in types. We call dunder methods as magic methods also. These dunder methods mainly used for operator overloading.
__getitem__ and __setitem__
As from below info, we know that getter and setter are magical methods. To implement getter and setter we use __getitem__ and __setitem__ methods. The main use of getter and setter methods for allocating the index. Examples are lists, arrays, dictionaries. We need to manipulate and access class attribute by ourselves. So, we use such methods to modify only by its own instances and to implement abstraction.
Simple Program on Operations
class Counter(object):
def __init__(self, floors):
self._floors = [None]*floors
def __setitem__(self, floor_number, data):
self._floors[floor_number] = data
def __getitem__(self, floor_number):
return self._floors[floor_number]
index = Counter(4)
index[0] = 'JAVA'
index[1] = 'TPOINT'
index[2] = 'CONTENT'
index[3] = 'WEBSITE'
print(index[1])
Output:
TPOINT
Suppose if we print two indexes. Let’s see
…..
Print (index [0])
Print (index [1])
Output:
JAVATPOINT
Let’ s discuss an example: a person bank record which contains transaction history, balance, and deposit etc. Now, we will perform many operations on this bank record as a built-in data type. To perform operations like check balance and transaction history which need access. If it directly modifies the balance then it may insert null values, or negative values. So, we use __getitem__and __setitem__ methods for presenting safely.
Example program:
classbank_record:
def__init__ (self, name):
self. record ={
"name": name,
"bal": 1000,
"transaction":[1000]
}
def__getitem__ (self, key):
returnself. record[key]
def__setitem__ (self, key, new value):
ifkey =="bal"andnew value! =Noneandnew value>=1000:
self. Record[key] +=new value
elifkey =="transaction"andnew value! =None:
self. Record[key]. append (new value)
defgetBal(self):
returnself. __getitem__("bal")
defupdateBal (self, new bal):
self. __setitem__ ("bal", new bal)
self. __setitem__ ("transaction", new bal)
defgetTransactions(self):
returnself. __getitem__("transaction")
defnumTransactions(self):
returnlen (self. Record["transaction"])
siri =bank record("siri")
print ("The balis: "+str (siri. getBal ()))
siri. updateBal (500)
print ("The new balis: "+str (siri. getBal ()))
print ("The no. of transactions are: "+str (siri. numTransactions ()))
siri. updateBal (200)
print ("The new balis: "+str (siri. getBal ()))
print ("The no. of transactions are: "+str (siri. numTransactions ()))
print ("The transaction history is: "+str (siri. getTransactions ()))
Output:
The balis: 1000
The new bal is: 1500
The number of transacions are: 2
The new bal is: 1700
The number of transactions are: 3
The transaction history is: [1000, 500, 200]
From below code, we can see that get Balance () and set Balance () methods are executed.
Uses of setitem, getitem and delitem:
Setitem:
Setitem() is used to call the attribute which is assigned by index.
Getitem:
Getitem () is used to assign the element to define this method in the class.
delitem:
delitem () is called when an element is deleted with the help of index.
Special magic methods are:
'__abs__', '__add__', '__and__', '__bool__', '__ceil__', '__class__', '__delattr__', '__dir__', '__divmod__', '__doc__', '__eq__', '__float__', '__floor__', '__floordiv__', '__format__', '__ge__', '__getattribute__', '__getnewargs__', '__gt__', '__hash__', '__index__', '__init__', '__init_subclass__', '__int__', '__invert__', '__le__', '__lshift__', '__lt__', '__mod__', '__mul__', '__ne__', '__neg__', '__new__', '__or__', '__pos__', '__pow__', '__radd__', '__rand__', '__rdivmod__', '__reduce__', '__reduce_ex__', '__repr__', '__rfloordiv__', '__rlshift__', '__rmod__', '__rmul__', '__ror__', '__round__', '__rpow__', '__rrshift__', '__rshift__', '__rsub__', '__rtruediv__', '__rxor__', '__setattr__', '__sizeof__', '__str__', '__sub__', '__subclasshook__', '__truediv__', '__trunc__', '__xor__'.