Home > Backend Development > Python Tutorial > Detailed explanation of the __getitem__ method in Python and the slicing operation of the slice object

Detailed explanation of the __getitem__ method in Python and the slicing operation of the slice object

WBOY
Release: 2016-07-06 13:29:52
Original
1460 people have browsed it

Although the Fib instance can be used in for loops and looks a bit like a list, it is still not possible to use it as a list. For example, take the 5th element:

>>> Fib()[5]
Traceback (most recent call last):
 File "<stdin>", line 1, in <module>
TypeError: 'Fib' object does not support indexing
Copy after login

To behave like a list and retrieve elements by subscript, you need to implement the __getitem__() method:

class Fib(object):
  def __getitem__(self, n):
    a, b = 1, 1
    for x in range(n):
      a, b = b, a + b
    return a
Copy after login

Now, you can access any item in the sequence by pressing the subscript:

>>> f = Fib()
>>> f[0]
1
>>> f[1]
1
>>> f[2]
2
>>> f[3]
3
>>> f[10]
89
>>> f[100]
573147844013817084101
Copy after login

slice object and __getitem__

To make instances of a class use subscripts like a list, you can set the __getitem__ method. For example:

class _List(object):

  def __getitem__(self, key):
    print key

l = _List()
l[3]  # print 3

Copy after login

But if you want to use slicing operation

l[1:4] # print slice(1, 4, None)
Copy after login

A slice object will be created for slicing. You can check the specific operation through help(slice).

a = slice(1, 4, None)

range(5)[a] # print [1, 2, 3]

Copy after login

More abundant operations

class _List(object):
  
  def __init__(self, _list):
    self._list = _list

  def __getitem__(self, key):
    if isinstance(key, int):
      return self._list[key]
    elif isinstance(key, slice):
      reutrn self.__class__(self._list[key])

if __name__ == '__main__':
  c = _List(range(10))
  b = c[1:5]
  print b[3] # print 4

Copy after login

If the key is an integer, return the list element. If it is a slice object, create an instance and return it.

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template