日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

__getitem__的作用

發布時間:2025/3/19 编程问答 23 豆豆
生活随笔 收集整理的這篇文章主要介紹了 __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__的作用的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。