Python Class: Object-oriented advanced programming __getitem__

Source: Internet
Author: User

Website Explanation:

  • object.__getitem__(Self, key)

  • Called to implement evaluation ofself[key].for sequence types,The accepted keys should beintegers andSlice Objects. Note that the special interpretation of negative indexes (if the class wishes to emulate a sequence type) are up to the__getitem__()Method. IfKeyis of a inappropriate type,TypeErrorMay is raised; If of a value outside the set of indexes for the sequence (after any special interpretation of negative values),IndexErrorshould be raised. For mapping types, ifKeyIs missing (not in the container),KeyErrorshould be raised.

    Note:

    forLoops expect that anIndexErrorWould be raised for illegal indexes to allow proper detection of the end of the sequence.


For the Fibonacci sequence, when we want to extract the value of a particular position to see, then what to do, and then come out __getitem__ such a function.


int, List type: Slice (no step)

#!/usr/bin/python

#-*-Coding:utf-8-*-


Class Fib (object):

def __getitem__ (self, N):

If Isinstance (n, int): # N is an index

A, B = 1, 1

For x in range (n):

A, B = B, A + b

Return a

If Isinstance (n, Slice): # N is a slice

Start = N.start

Stop = N.stop

If Start is None:

Start = 0

A, B = 1, 1

L = []

For x in range (stop):

If x >= start:

L.append (a)

A, B = B, A + b

Return L

f = Fib ()

Print F[0:4]

Print F[9]

Python Class: Object-oriented advanced programming __getitem__

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.