Getitem и setitem python

Using Python __getitem__ and __setitem__

I have always said that I am really fond of Python language. Today I am going to show you another big reason for the same. Python gives most of the flexibility for the developers to develop their code efficiently. And that is why Python allows its user to create their custom classes using the inbuilt classes such as list, str, etc.

Today I am going to demonstrate how to create your own custom datatype like list in Python. We are also going to add some custom fun texts to get things interesting. Now, before going for the actual implementation, consider the following code snippet:

 # create a list with some arbitrary elements my_list = [1, 2, 3] # print the list print(my_list) [1, 2, 3] # Set the item at index 0 to a value of 4 >>> my_list[0] = 4 # Print the value at index 0 >>> print(my_list[0]) 4 

As you can observe from above code, we can create a list and then set a value for a specified index and get the value at the specified index. We will be using the same functionality in our custom class that we are about to create.

Initially, we will be creating a simple class with a constructor that we initialize our list with zeros.

 # create our custom list class class CustomList(object): # constructor def __init__(self, elements=1): self.my_custom_list = [0] * elements 

In the above code snippet, what I have done is I have created a simple class called CustomList . The constructor of the class i.e __init__() will initialize our my_custom_list with number of elements that user has specified.

The next step is to wite our own member function to print our my_custom_list. For that simply add the following code to the above code:

 def __str__(self): return 'Hey these are my contents: ' + str(self.my_custom_list) 

__str__() is called Magic Method in Python. There are various magic methods in Python and we will be using some of them in a minute. But for now let us understand what is __str__() . So basically, __str__() is a special method which is used to specify the formatting of your class object. In simple words, whenever you call a print() on your class object, str specifies what should get printed on that time. Let us try to print our CustomList class now.

 print(CustomList()) # It prints Hey these are my contents: [0] 

Wow! That’s something amazing right. We have successfully created our own class and now we can even print some custom text.

If you have observed in the first code snippet, Python lists can set a value for a specified index and get the value at the specified index. Now, we will be adding these functionalities to our class too. This is how its done:

 # add the following code your class # For setting the value def __setitem__(self, index, value): self.my_custom_list[index] = value # For getting the value from our custom_list def __getitem__(self, index): return "Hey you are accessing <> element whose value is: <>".format(index, self.my_custom_list[index]) 

If we run our program after adding above lines we get something similar as:

 # Create my_custom_list with 12 elements obj = CustomList(12) # Set value at index 0 to 1 obj[0] = 1 # print value at index 0 print(obj[0]) # print the whole my_custom_list print(obj) # Output: Hey you are accessing 0 element whose value is: 1 [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] 

Ahaa! Now we can even set an item and retrieve an item from our CustomList class with custom text. Now, you can further play with other magic methods and create your own Custom classes.

 class CustomList(object): def __init__(self, elements=0): self.my_custom_list = [0] * elements def __setitem__(self, index, value): self.my_custom_list[index] = value def __getitem__(self, index): return "Hey you are accessing <> element whose value is: <>".format(index, self.my_custom_list[index]) def __str__(self): return str(self.my_custom_list) obj = CustomList(12) obj[0] = 1 print(obj[0]) print(obj) 

Hope you enjoyed this small tutorial 🙂

Читайте также:  Java simple parser xml

Happy Coding!

All content is licensed under the CC BY-SA 4.0 License unless otherwise specified

Источник

Магические методы __getitem__, __setitem__ и __delitem__

В объекте s1 имеется локальное свойство marks со списком студентов. Мы можем к нему обратиться и выбрать любую оценку:

Если сейчас запустить программу, то увидим сообщение об ошибке, что наш класс (объект) не поддерживает такой синтаксис. Как вы, наверное, уже догадались, поправить это можно с помощью магического метода __getitem__. Запишем его в нашем классе, следующим образом:

def __getitem__(self, item): return self.marks[item]

то получим исключение IndexError, которое сгенерировал список marks. При необходимости, мы можем сами контролировать эту ошибку, если в методе __getitem__ пропишем проверку:

def __getitem__(self, item): if 0  item  len(self.marks): return self.marks[item] else: raise IndexError("Неверный индекс")

При запуске программы видим наше сообщение «Неверный индекс». Также можно сделать проверку на тип индекса:

def __getitem__(self, item): if not isinstance(item, int): raise TypeError("Индекс должен быть целым числом") if 0  item  len(self.marks): return self.marks[item] else: raise IndexError("Неверный индекс")

То есть, здесь возможны самые разные вариации обработки и проверки исходных данных, прежде чем обратиться к списку marks и вернуть значение. Теперь давайте предположим, что хотели бы иметь возможность менять оценки студентов, используя синтаксис:

Сейчас, после запуска программы будет ошибка TypeError, что объект не поддерживает операцию присвоения, так как в классе не реализован метод __setitem__. Давайте добавим и его:

def __setitem__(self, key, value): if not isinstance(key, int) or key  0: raise TypeError("Индекс должен быть целым неотрицательным числом") self.marks[key] = value

то операция присвоения новой оценки приведет к ошибке. Если предполагается использовать такую возможность, то реализовать ее можно, следующим образом:

def __setitem__(self, key, value): if not isinstance(key, int) or key  0: raise TypeError("Индекс должен быть целым неотрицательным числом") if key >= len(self.marks): off = key + 1 - en(self.marks) self.marks.extend([None]*off) self.marks[key] = value

Если индекс превышает размер списка, то мы расширяем список значениями None до нужной длины (с помощью метода extend), а затем, в последний элемент записываем переданное значение value. Теперь, при выполнении команд:

Увидим список: [5, 5, 3, 2, 5, None, None, None, None, None, 4] То есть, он был расширен до 10 элементов и последним элементом записано 4. И так можно прописывать любую нужную нам логику при записи новых значений в список marks. Наконец, последний третий магический метод __delitem__ вызывается при удалении элемента из списка. Если сейчас записать команду:

то в консоли увидим сообщение: «AttributeError: __delitem__». Здесь явно указывается, что при удалении вызывается метод __delitem__. Добавим его в наш класс:

def __delitem__(self, key): if not isinstance(key, int): raise TypeError("Индекс должен быть целым числом") del self.marks[key]

Источник

__getitem__ and __setitem__ in Python

Have you ever considered how Python’s magic methods make our lives as programmers less complicated, almost as if we’ve got a helpful buddy guiding us along the way? In this article, we’re going to explore Python’s magic methods, getitem, and setitem, unraveling their mysteries and coming across how they are able to assist us to write extra expressive, human-friendly code. Let’s dive in!

Understanding Magic Methods

Magic methods, additionally called «dunder» methods (short for «double underscore»), are unique strategies in Python classes that have double underscores at the beginning and cease of their names. They permit us to define how our classes ought to behave in positive situations, like when we want to get the right of entry to or regulate their factors. Two of these magic methods are getitem and setitem, which might be used to define how we retrieve and regulate the factors of a custom magnificence.

The Magic of Getitem

The getitem magic method allows us to define how to access elements of a custom class using the square bracket notation, just like we would with lists, dictionaries, or other built-in Python objects. When we define a class with a getitem method, we can access its elements using the familiar syntax −

element = my_instance[index]

Here’s an example of a simple custom class called MyList, which simulates a basic list using the getitem magic method −

Step 1 − Define the MyList class with a constructor (__init__) that takes a list as input and feeds it inside the data attribute.

Step 2 − Implement the __getitem__ magic approach, which takes an index as an argument and returns the element from the data attribute at the given index.

Step 3 − Create an example of MyList with a listing of numbers from 1 to 5.

Step 4 − Print the element at index 1 using the square bracket notation. The output will be 2.

Example

class MyList: def __init__(self, data): self.data = data def __getitem__(self, index): return self.data[index] my_list = MyList([1, 2, 3, 4, 5]) print(my_list[1])

Output

The Enchantment of Setitem

Now that we’ve explored getitem, let’s take a look at its counterpart, setitem. The setitem magic method allows us to define how to modify elements of a custom class using the square bracket notation. When we define a class with a setitem method, we can modify its elements like this −

my_instance[index] = new_value

Let’s expand our previous MyList example to include the setitem magic method −

Step 1 − Characterize the MyList class with a constructor (__init__) that takes a listing as input and stores it inside the data attribute.

Step 2 − Implement the __getitem__ magic method, which takes an index as an argument and returns the detail from the data characteristic at the given index.

Step 3 − Execute the __setitem__ magic method, which takes an index and a price as arguments, and relegates the cost to the thing inside the data characteristic on the given index.

Step 4 − Make an instance of MyList with a listing of numbers from 1 to 4.

Step 5 − Print the element at index 1 using the square bracket notation. The output will be 2.

Step 6 − Modify the element at index 1 by assigning a new value (42) using the square bracket notation. The __setitem__ method will handle the modification.

Step 7 − Print the element at index 1 again using the square bracket notation. Due to the modification in Step 6, the output will now be 42.

Example

class MyList: def __init__(self, data): self.data = data def __getitem__(self, index): return self.data[index] def __setitem__(self, index, value): self.data[index] = value my_list = MyList([1, 2, 3, 4, 5]) print(my_list[1]) # Output: 2 my_list[1] = 42 print(my_list[1])

Output

Best Practices for Using Getitem and Setitem

Now that we understand the magic of getitem and setitem, let’s review some best practices for using these methods to create more human-friendly code −

  • Make your code intuitive − When using getitem and setitem, aim for intuitive behavior that resembles built-in Python objects like lists, dictionaries, or arrays. This will make your custom classes more approachable and easier to understand.
  • Handle edge cases gracefully − Be prepared to handle edge cases, such as invalid indices or keys. You can raise appropriate exceptions, like IndexError for invalid indices or KeyError for invalid keys, to inform users about the issue.
  • Use clear variable names − When defining your getitem and setitem methods, use clear and descriptive variable names for indices and values. This will make your code more readable and less difficult to manage.
  • Don’t forget about slicing − Consider supporting slicing operations in your getitem and setitem methods, making your custom classes even more versatile and convenient to work with.
  • Stay consistent − If your class implements both getitem and setitem, ensure their behavior remains consistent. For instance, if your getitem method supports negative indices, your setitem method should do the same.

Conclusion

In this article, we’ve explored the magical world of getitem and setitem magic methods. These powerful tools enable us to create custom classes with intuitive and familiar behavior, mimicking built-in Python objects and making our code more expressive and human-friendly.

By following the best practices we’ve discussed, you’ll be able to harness the power of getitem and setitem to create custom classes that feel like second nature to your fellow programmers, fostering collaboration and understanding. So go ahead and spread the magic of getitem and setitem throughout your Python projects, creating code that’s as enchanting as it is functional. Happy coding!

Источник

Оцените статью