取第5个元素:
>>> Fib()[5]
Traceback (most recent call last):
File "", line 1, in
TypeError...原因是__getitem__()传入的参数可能是一个int,也可能是一个切片对象slice,所以要做判断
class Fib(object):
def __getitem__(self, n):...step参数作处理:
>>> f[:10:2]
[1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
如果把对象看成dict,__getitem__()的参数也可能是一个可以作key...getattr__(self, attr):
if attr=='age':
return lambda: 25
只是调用方式要变为:
>>> s.age()
25
只有在没有找到属性的情况下...,才调用__getattr__,已有的属性,比如name,不会在__getattr__中查找。