×

__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__'.


Related Topics

Python object()

Python object() class The object class in Python is a base for all classes. It returns a new featureless object. Syntax class object Parameter NA Return It returns a new featureless object. Example 1 # Python program explaining # the object()...

1 minute read.

Image to Text in python

Processing out information from an image is a very big task in all the fields of work such as in development and business sector. The process of converting an electronical...

3 minutes read.

List in Python

What is List in Python In Python, lists are used to store the multiple values in one variable. We can say that list is the collection of similar as well as...

3 minutes read.

Python for Loop Increment

Introduction In general, loops are employed for sequential traversal. It belongs to the definite iteration category. Definite iterations imply that the number of iterations is explicitly set in advance.  In this article,...

4 minutes read.

Iterators in Python

Introduction In Python, an iterator is defined as an object that enables traversing through all the values of a collection. It contains the countable number of values. The iterator is utilized to...

4 minutes read.

Check whether dir is empty or not in python

Python: Check if a directory is empty In this tutorial, we will study how to check whether the director (dir) is empty or not in the python programming language. First of...

3 minutes read.

PyShark in Python

Python: Python is an interactive and more accessible language than any other programming language. The python programming language uses a variety of libraries to perform the operations in a faster way....

4 minutes read.

Check Palindrome in Python

Python is an object-oriented high-level programming language. Python has dynamic semantics and has high-level built-in data structures which support dynamic typing and dynamic binding. Python provides rapid development. It has...

4 minutes read.

BOTTLE Python Web Framework

The Bottle is a lightweight WSGI micro web framework for python. It acts like a thin wrapper around a web server where it is distributed as a single file module...

4 minutes read.

Difference between Yield and Return in Python

Python yield statement The generators are defined by using the yield statement in Python. Generally, it converts a normal Python function into a generator.  The yield statement hauls the function and returns...

3 minutes read.

Python program to find the area of the triangle

Python program to find the area of the triangle This article will discuss how to find the area of a triangle in Python with all three given sides. The area of...

2 minutes read.

Python Pascal Triangle

Python Pascal Triangle Pascal triangle A pascal triangle is a number pattern of triangular array of the binomial coefficients. For designing a pascal triangle, we write a function in the program which...

5 minutes read.

Scrimba python

Scrimba allows you to study whenever and wherever the topics or concepts you want. It also replaces classroom instruction with interactive screencasts, live events, and student-to-student help. Scrimba is an interactive...

3 minutes read.

Python exit commands

exit(), quit(), sys.exit(), os._exit() In this tutorial, we will study exit commands used in the Python programming language. Python is undoubtedly the choice of programmer and this is because of the in-built...

3 minutes read.

Python Queue

Python Queue There are various day to day activities where we find ourselves engaged with queues. Whether it is waiting in toll tax lane or standing on the billing counter for...

7 minutes read.

Python Pass Statement

The pass statement is a null statement. The difference between pass and comment is that comment is ignored by the interpreter, whereas pass is not. The pass statement is typically used...

3 minutes read.

Python Printf Style Formating

String objects have one special implicit activity: the % administrator (modulo). This is otherwise called the string designing or interjection administrator. Given design % values (where configuration is a string),...

3 minutes read.

Get Bounding Box Co-ordinates Python

Python: Python is an interactive and more accessible language than any other programming language. The python programming language uses a variety of libraries to perform the operations in a faster way....

6 minutes read.

Python Os sep

Python: Python is an interactive and more accessible language than any other programming language. The python programming language uses a variety of libraries to perform the operations in a faster way....

3 minutes read.

Python String splitlines() method

Python String splitlines() method The string.splitlines() method in Python splits the specified string and returns a list of the lines in the string, breaking at line boundaries.  Syntax splitlines([keepends]) Parameter keepends(optional): This parameter specifies if...

1 minute read.