转载:https://www.cnblogs.com/PrettyTom/p/6659425.html
python定制类(1):__getitem__
1.__getitem__的简单用法:
- 当一个类中定义了__getitem__方法,那么它的实例对象便拥有了通过下标来索引的能力。
class A(object):
def __getitem__(self, item):
return item
a = A()
print(a[5], a[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