1.__getitem__的简单用法:
当一个类中定义了getitem方法,那么它的实例对象便拥有了通过下标来索引的能力。
class A(object):
def __getitem__(self, item):
return item
a = A()
print(a[5], a[12])
执行结果:
5 12
2.用getitem实现斐波那契数列:
class Fib(object):
def __getitem__(self, item):
if item == 0 or item == 1:
return 1
else:
a, b = 1, 1
for i in range(item - 1):
a, b = b, a+b
return b
fib = Fib()
for i in range(10):
print(fib[i])
执行结果:
1
1
2
3
5
8
13
21
34
55
3.slice切片
我们发现上个程序fib[2]这样的一个下标是没问题的,不过fib[3:5]这样的切片的话是会报错的。所以我们先了解下什么是切片。
# slice用法:
# slice(stop)
# slice(start, stop, step)
>>> a = slice(10)
>>> print(a)
slice(None, 10, None)
>>> a = slice(1,10,2)
>>> print(a)
slice(1, 10, 2)
>>> print(a.start)
1
>>> print(a.stop)
10
>>> print(a.step)
2
>>> li = [1,2,3,4,5,6,7,8,9,0]
>>> li[slice(2,6)]
[3, 4, 5, 6]
#是的。li[slice(2,6)] 就等于 li[2:6]
给斐波那契数列完成slice切片:
class Fib(object):
def __getitem__(self, item):
if isinstance(item, slice):
print(item.start)
print(item.stop)
stop = item.stop
if item.stop is None:
stop = 100
re_list = []
a, b = 0, 1
for i in range(stop):
a, b = b, a + b
re_list.append(a)
return re_list[item.start:stop:item.step]
elif item == 0 or item == 1:
return 1
else:
a, b = 1, 1
for i in range(item - 1):
a, b = b, a+b
return b
fib = Fib()
print(fib[1:20:2])
输出结果:
1
20
[1, 3, 8, 21, 55, 144, 377, 987, 2584, 6765]