__getitem__本质上将一个对象具有字典功能
案例一:
class Text__getitem__():
def __init__(self):
pass
def __len__(self):
return 3
def __getitem__(self, key):
if key.startswith("abc"):
return "abc"
elif key.startswith("bcd"):
return "bcd"
else:
return "nonono"
obj = Text__getitem__()
print(obj["abc"])
输出:abc
案例二:
class Text__getitem__():
def __init__(self):
pass
def __len__(self):
return 3
def __getitem__(self, key):
if key.startswith("abc"):
return "abc"
elif key.startswith("bcd"):
return "bcd"
else:
return "nonono"
obj = Text__getitem__()
print(obj["abc"])
for k, v in enumerate(obj):
print(k, v)
输出:
abc
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-90-24e3e74a5609> in <module>
14 print(obj["abc"])
15
---> 16 for k, v in enumerate(obj):
17 print(k, v)
<ipython-input-90-24e3e74a5609> in __getitem__(self, key)
5 return 3
6 def __getitem__(self, key):
----> 7 if key.startswith("abc"):
8 return "abc"
9 elif key.startswith("bcd"):
AttributeError: 'int' object has no attribute 'startswith'
案例三:
class Text__getitem__():
def __init__(self):
pass
def __len__(self):
return 3
def __getitem__(self, key):
if key < 0 or key >= 3:
raise IndexError
if key == 1:
return "abc"
elif key == 2:
return "bcd"
else:
return "nonono"
obj = Text__getitem__()
for k, v in enumerate(obj):
print(k, v)
输出:
0 nonono
1 abc
2 bcd
这两句代码非常重要,否则就会key值就会一直循环下去。
if key < 0 or key >= 3:
raise IndexError
案例四、
class Text__getitem__():
def __init__(self):
pass
def __len__(self):
return 3
def __getitem__(self, key):
if key == 1:
return "abc"
elif key == 2:
return "bcd"
else:
return "nonono"
obj = Text__getitem__()
for k, v in enumerate(obj):
print(k, v)
输出:
0 nonono
1 abc
2 bcd
3 nonono
4 nonono
5 nonono
6 nonono
7 nonono
8 nonono
9 nonono
10 nonono
11 nonono
12 nonono
13 nonono
14 nonono
15 nonono
16 nonono
17 nonono
18 nonono
19 nonono
20 nonono
21 nonono
……