__getitem__的作用
生活随笔
收集整理的這篇文章主要介紹了
__getitem__的作用
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
?__getitem__本質上將一個對象具有字典功能
案例一:
class Text__getitem__():def __init__(self):passdef __len__(self):return 3def __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):passdef __len__(self):return 3def __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 36 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):passdef __len__(self):return 3def __getitem__(self, key):if key < 0 or key >= 3: raise IndexErrorif 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):passdef __len__(self):return 3def __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 ……?
總結
以上是生活随笔為你收集整理的__getitem__的作用的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: pytorch model.eval()
- 下一篇: __len__的作用