__getitem__()
__getitem__()
即可。所以,这里就先介绍一下这个方法。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.
__getitem__()
方法用于返回参数 key 所对应的值,这个 key 可以是整型数值和切片对象,并且支持负数索引;如果 key 不是以上两种类型,就会抛 TypeError;如果索引越界,会抛 IndexError ;如果定义的是映射类型,当 key 参数不是其对象的键值时,则会抛 KeyError 。class MyList():
def __init__(self):
self.data = []
def append(self, item):
self.data.append(item)
def __iter__(self):
return self
def __getitem__(self, key):
print("key is : " + str(key))
return self.data[key]
l = MyList()
l.append("My")
l.append("name")
l.append("is")
l.append("Python猫")
print(l[3])
print(l[:2])
print(l['hi'])
### 输出结果:
key is : 3
Python猫
key is : slice(None, 2, None)
['My', 'name']
key is : hi
Traceback (most recent call last):
...
TypeError: list indices must be integers or slices, not str
#####
2018-12-31 更新声明:本例未考虑到返回类型,严格来说并未实现切片。
在合并的文章里已做修正:https://mp.weixin.qq.com/s/IRAjR-KHZBPEEkdiofseGQ
__getitem__()
方法会根据不同的参数类型而实现不同的功能(取索引位值或切片值),也会妥当地处理异常,所以并不需要我们再去写繁琐的处理逻辑。###略去其它代码####
def __getitem__(self, index):
cls = type(self)
if isinstance(index, slice): # 如果index是个切片类型,则构造新实例
return cls(self._components[index])
elif isinstance(index, numbers.Integral): # 如果index是个数,则直接返回
return self._components[index]
else:
msg = "{cls.__name__} indices must be integers"
raise TypeError(msg.format(cls=cls))
class MyDict():
def __init__(self):
self.data = {}
def __len__(self):
return len(self.data)
def append(self, item):
self.data[len(self)] = item
def __getitem__(self, key):
if isinstance(key, int):
return self.data[key]
if isinstance(key, slice):
slicedkeys = list(self.data.keys())[key]
return {k: self.data[k] for k in slicedkeys}
else:
raise TypeError
d = MyDict()
d.append("My")
d.append("name")
d.append("is")
d.append("Python猫")
print(d[2])
print(d[:2])
print(d[-4:-2])
print(d['hi'])
### 输出结果:
is
{0: 'My', 1: 'name'}
{0: 'My', 1: 'name'}
Traceback (most recent call last):
...
TypeError
__getitem__()
魔术方法,并用于实现自定义对象(以列表类型和字典类型为例)的切片功能,希望对你有所帮助。