Python. Overloading of operators. Accessing elements by index

Overloading of operators. Accessing elements by index. Methods __getitem__() and __setitem__()


Contents


Search other resources:

1. Overload access by index []. Method __getitem__()

To provide access by index in the class, you need to implement the __getitem__() and __setitem__() methods. As a rule, access by index is required in classes that implement data sets (arrays, lists, etc.).

The __getitem__() method is called when the data needs to be read by index. An approximate form of a method declaration in a class might be as follows

class ClassName:
    # Components of the class

    ...

    def __getitem__(self, index):
        ...
        return self.objName[index]

here

  • ClassName – class name;
  • objName – iterated object that is a list, tuple, etc.;
  • index – position (index) of the element in the objName object.

You can, of course, implement the __getitem__() method for a non-iterated object as well, giving it a certain meaning.

After declaring the __getitem__() method, you can access the class object in the usual way using square brackets [ ]

value = ClassName[index] # method __getitem__() is called

here

  • value – some value;
  • index – position (index) of the iterated object in the ClassName class.

  ⇑

2. Overload access by index [ ]. Setting a new value. Method __setitem__()

The __setitem()__ method is called when it is necessary to write data by index to the class object. This class object is usually a list, a tuple, and so on. Using the __setitem__() method in a class could be something like this

def ClassName:
    # Components of the class

    ...

    def __setitem__(self, index, newValue):
        self.objName[index] = newValue

here

  • ClassName – the name of class;
  • objName – the name of the iterated object for which the value of newValue is set at position index;
  • index – position starting from 0;
  • newValue is the new value set in the objName object.

After implementing the __setitem__() method in a class, you can write data to the iterated object of the class. It looks like this

ClassName[index] = newValue

here

  • ClassName – class name containing the iterated object;
  • index – element position in the iterated object;
  • newValue – new value.

  ⇑

3. An example demonstrating the implementation of an array of complex numbers and index access to array elements

The example declares an ArrayComplex class that contains the following components:

  • AC – the name of an array of complex numbers. The array is organized as a list. Each array element represents a (re, im) pair, which is a tuple;
  • __init__() is a constructor. Creates an empty AC list;
  • method Add() – provides adding a new complex number to the array. The number is attached as a tuple of the form (re, im) consisting of the real part of the complex number (re) and the imaginary part of the complex number (im);
  • Count() method – returns the length of the AC list;
  • method Print() – displays a list of complex numbers in a convenient form;
  • method __getitem__() – provides reading by the index of the AC list element;
  • method __setitem__() – ensures that a given value is written to the list of AC numbers at a given position (index).

 

# Access by index. Overloading methods __getitem__(), __setitem__()
# A class that implements an array of complex numbers
class ArrayComplex:
    # 1. Class constructor
    def __init__(self):
        # the array is implemented as a list named AC
        self.AC = [] # create an empty list
        return

    # 2. A method that adds a complex number to a list.
    # The number is added as a tuple.
    # Here re is the real part of a complex number,
    # im - imaginary part of a complex number.
    def Add(self, re, im):
        self.AC = self.AC + [(re, im)]

    # 3. Method that returns the number of array elements
    def Count(self):
        return len(self.AC)

    # 4. Method that displays a list of complex numbers on the screen
    def Print(self, msg):
        s = msg + " => [ "
        for c in self.AC:
            s = s + "(" + str(c[0]) + ", " + str(c[1]) + ") "
        s = s + "]"
        print(s)

    # 5. Methods that provide access by index []
    # 5.1. Reading array element by index
    def __getitem__(self, index):
        return self.AC[index]

    # 5.2. Write element by index,
    # value is a tuple of type (re, im)
    def __setitem__(self, index, value):
        self.AC[index] = value

# ------- Using the class -------
# 1. Create an object of ArrayComplex class
AC = ArrayComplex()

# 2. Add multiple numbers
AC.Add(5, 8)
AC.Add(2, -4)
AC.Add(-3.5, -1.8)
AC.Add(2.8, 1)

# 3. Print the contents of the AC object
AC.Print("AC")

# 4. Read the first element of an array
cm1 = AC[0] # AC.__getitem__(0) is called
print("cm1 = ", cm1)

# Read the last element of an array
cm2 = AC[AC.Count()-1]
print("cm2 = ", cm2)

# 5. Write the new value to the array at position 1
AC[1] = (10, 20) # AC.__setitem__(1, (10, 20)) is called

# 6. Display the array
AC.Print("AC")

# 7. Get the slice object and output the slice.
objSlice = AC[:AC.Count()]
print("Slice[:Count()-1] => ", objSlice)

# 8. Get the slice containing the first 2 elements
objSlice = AC[:3]
print("Slice[:2] => ", objSlice)

Result

AC => [ (5, 8) (2, -4) (-3.5, -1.8) (2.8, 1) ]
('cm1 = ', (5, 8))
('cm2 = ', (2.8, 1))
AC => [ (5, 8) (10, 20) (-3.5, -1.8) (2.8, 1) ]
('Slice[:Count()-1] => ', [(5, 8), (10, 20), (-3.5, -1.8), (2.8, 1)])
('Slice[:2] => ', [(5, 8), (10, 20), (-3.5, -1.8)])

  ⇑

4. An example demonstrating access to a class object by index. Implementing the Point and ListPoints classes

 

# Access by index
# A class that describes a point on the coordinate plane,
# the class uses internal fields x, y
class Point:
    # 1. Class constructor
    def __init__(self, x, y):
        self.x = x
        self.y = y
        return

    # 2. Access methods
    # 2.1. Set a new value of x
    def SetXY(self, x, y):
        self.x = x
        self.y = y
        return

    # 2.2. Read x, y
    def X(self) : return self.x
    def Y(self) : return self.y

    # Method that displays a point on the screen
    def Print(self, msg):
        s = msg + " = (" + str(self.x) + "; " + str(self.y) + ")";
        print(s)

# A class that describes an array of points named AP
class ListPoints:
    # constructor
    def __init__(self):
        self.AP = [] # Create an empty list

    # A method that adds a point to the end of a list.
    def Add(self, pt):
        self.AP = self.AP + [pt]

    # Method that returns a list of points
    def GetList(self): return self.AP

    # Method that displays a list of points
    def Print(self, msg):
        s = msg + " = [" # generate an output string
        for p in self.AP:
            s = s + "(" + str(p.X()) + "; " + str(p.Y()) + ") "
        print(s + ']\n')

    # Methods that implement access by index
    # Get point by index
    def __getitem__(self, index):
        return self.AP[index]

    # Write a new point at index position
    def __setitem__(self, index, value):
        self.AP[index] = value

# ------- Using classes Point и ListPoints -------
# 1. Create a point
p1 = Point(2, 8.3)
p1.Print("p1")

# 2. Create an array of points of type Point
# 2.1. Create the empty array
ArrayPoints = ListPoints()

# 2.2. Add 3 points to array
ArrayPoints.Add(p1) # Add point p1
ArrayPoints.Add(Point(3, 7.1)) # add point (3, 7.1)
ArrayPoints.Add(Point(2, 1.6))

# 2.3. Output array of points
ArrayPoints.Print("ArrayPoints")

# 3. Read point with index 0
pt = ArrayPoints[0] # here the __getitem__() method is called
pt.Print("ArrayPoints[0]")

# 4. Write a new value to the point with index 1
ArrayPoints[1] = Point(1.5, 2.3) # call the __setitem__() method

# 5. Display the array
ArrayPoints.Print("ArrayPoints")

Result

p1 = (2; 8.3)
ArrayPoints = [(2; 8.3) (3; 7.1) (2; 1.6) ]

ArrayPoints[0] = (2; 8.3)
ArrayPoints = [(2; 8.3) (1.5; 2.3) (2; 1.6) ]

  ⇑


Related topics

  ⇑