Describes the _ getitem _ method in Python and slice object slicing operations,

Source: Internet
Author: User

Describes the _ getitem _ method in Python and slice object slicing operations,

Although the Fib instance can act on a for loop, it looks a little like a list, but it still cannot be used as a list, for example, taking 5th elements:

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

To retrieve elements by subscript like list, the _ getitem _ () method must be implemented:

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

Now, you can access any of the series by Subscript:

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

Slice object and _ getitem __

You can set the _ getitem _ method to make the instance of the class use the subscript like the list. For example:

class _List(object):  def __getitem__(self, key):    print keyl = _List()l[3]  # print 3

However, if you want to use the slice operation

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

A slice object is created for slicing. You can view the specific operation through help (slice.

a = slice(1, 4, None)range(5)[a] # print [1, 2, 3]

Richer 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

If the key is an integer, the list element is returned. If the key is an slice object, an instance is created and a result is returned.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.