python getitem_python Class:面向对象高级编程 __getitem__

官网解释:object.__getitem__(self, key)

Called to implement evaluation of self[key]. For sequence types,the accepted keys should beintegersandslice 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数列,当我们想抽取特定位置的值看,那又该怎么做,于是就出来了__getitem__这样的函数。

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]

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值