×

__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

Selection Sort Using Python

Selection sort is a type of sorting algorithm which is based on sorting elements in increasing order or ascending order through comparison. This sorting technique does not take extra space...

3 minutes read.

Python Line Break

Introduction In this tutorial, you will learn line breaks in python.In Python, the new line character is used to indicate the start of a new line and the end of an...

5 minutes read.

Python NewLine

In python, a new line character denoted by "\n" is known as an escape character or escape sequence, and it will force the cursor to change its position to the next...

6 minutes read.

Python Linear regression

In this tutorial, we will understand the meaning, usage, and types of Linear Regression. Further, we will comprehend the terms cost function and Optimization. Linear Regression is the widely used Machine...

3 minutes read.

Python random.seed() function

The random module in Python produces a random number or pseudo-random data, that is, deterministic. The seed function records the state of a random function to provide the same random...

6 minutes read.

Python String lstrip() method

Python String lstrip() method The string. lstrip () method in Python returns a copy of the string with leading characters removed (based on the string argument passed). Syntax string.lstrip([chars]) Parameter chars(optional): This parameter represents a...

1 minute read.

Python enumerate() function

Python enumerate() function The enumerate() function in Python takes a collection (e.g. a tuple) and returns it as an enumerate object. Syntax: enumerate(iterable, start=0) Parameter Iterable:  This parameter represents an iterable object start:    This parameter represents a number defining...

1 minute read.

Python - Binomial Distribution

Introduction Definition of the Binomial Distribution The method of counting how many instances of a specific event there have been is called the binomial distribution. It will outline the possible outcomes or...

4 minutes read.

Python Read CSV file

The CSV stands for “comma-separated value,” which is defined as a simple file format that is used to store data into a tabular form such as a database or spreadsheet. It is...

7 minutes read.

Python Online Compiler

Compose, Run and Offer Python code internet involving OneCompiler's Python online compiler free of charge. It's one of the hearty, highlight-rich web-based compilers for python language, supporting both the adaptations, which...

3 minutes read.

Python Sys Stdout

Python Programming Language: Python programming language is one of the most used programming languages, as it is used widely in the field of software and data analysis, web development, etc. It...

3 minutes read.

What does base case mean in recursion

Base cases and recursive stages are used to define recursive functions. In a primary subject, we compute the outcome right away, given the function call's arguments. In a recursive step, we...

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.

How to read data from com port in python

Comport, the I/O interface is known as a COM port that allows the connection for a serial device to a computer. COM ports are sometimes referred to as serial ports....

3 minutes read.

Creating Web Application in python

Web Application :  Web Application is an application software that runs in web browser . Software programs will run on operating system. Whereas Web Applications will run on World Wide Web...

5 minutes read.

Python Set intersection() method

Python Set intersection() method The set.intersection() method in Python returns a new set with elements that are similar between two or more sets. Syntax set.intersection(set1, set2 ... etc) Parameter set1- This parameter represents the set to search for...

2 minutes read.

Python eval() function

Python eval() function The eval() function in Python is used to evaluate the given expression. If the specified expression is a legal Python statement, it will be executed. Syntax eval(expression, globals=None, locals=None) Parameter expression: This parameter represents a String,...

1 minute read.

Python System Requirements

Introduction As we know, Python is a popular programming language usually used to write scripts for operating systems. It’s handy adequate for utilizing in web development and application design. In this article,...

2 minutes read.

Looping through Data Frame in Python

Iterate over Rows and Columns in Pandas Dataframe This tutorial aims to make us understand what Pandas in Python are, what Data Frame in Python is and its significance, what are...

4 minutes read.

Assertion Errors and Attribute Errors in Python

Assertion Error in Python In Python, the assert condition is used to continue the execution if the given statement displays true. If the assert statement displays false, it raises Assertion Error...

3 minutes read.