您好,登錄后才能下訂單哦!
官網(wǎng)解釋:
object.
__getitem__
(self, key)
Called to implement evaluation of self[key]
. For sequence types, the accepted keys should be integers and slice objects. Note that the special interpretation of negative indexes (if the class wishes to emulate a sequence type) is up to the __getitem__()
method. If key is of an inappropriate type, TypeError
may be raised; if of a value outside the set of indexes for the sequence (after any special interpretation of negative values), IndexError
should be raised. For mapping types, if key is missing (not in the container), KeyError
should be raised.
Note:
for
loops expect that an IndexError
will be raised for illegal indexes to allow proper detection of the end of the sequence.對于Fibonacci數(shù)列,當(dāng)我們想抽取特定位置的值看,那又該怎么做,于是就出來了__getitem__這樣的函數(shù)。
int、list類型:切片(沒有step)
#!/usr/bin/python
# -*- coding: utf-8 -*-
class Fib(object):
def __getitem__(self, n):
if isinstance(n, int): # n是索引
a, b = 1, 1
for x in range(n):
a, b = b, a + b
return a
if isinstance(n, slice): # n是切片
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]
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報,并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。