久久久久久久av_日韩在线中文_看一级毛片视频_日本精品二区_成人深夜福利视频_武道仙尊动漫在线观看

如何使用 __getitem__ 和 __iter__ 并從字典中返回值

How do I use __getitem__ and __iter__ and return values from a dictionary?(如何使用 __getitem__ 和 __iter__ 并從字典中返回值?)
本文介紹了如何使用 __getitem__ 和 __iter__ 并從字典中返回值?的處理方法,對大家解決問題具有一定的參考價值,需要的朋友們下面隨著小編來一起學習吧!

問題描述

我有一個帶有字典的對象,我想通過 __getitem__ 訪問該對象并對其進行迭代(僅值,鍵無關緊要),但不知道該怎么做.p>

例如:

Python 2.5.2 (r252:60911, Jul 22, 2009, 15:33:10)>>>類庫(對象):... def __init__(self):... self.books = {'title':對象,'title2':對象,'title3':對象,}... def __getitem__(self, i):...返回 self.books[i]...>>>圖書館=圖書館()>>>圖書館['標題']<輸入對象">>>>圖書館借書:... 打印書...回溯(最近一次通話最后):<module> 中的文件<stdin>"第 1 行文件<stdin>",第 5 行,在 __getitem__ 中關鍵錯誤:0>>>

我如何告訴它為字典中的每個項目簡單地返回 object (鍵無關緊要)?

解決方案

def __iter__(self): return self.books.itervalues()

I have an object with a dictionary that I want to access via __getitem__ as well as iterate over (values only, keys don't matter) but am not sure how to do it.

For example:

Python 2.5.2 (r252:60911, Jul 22 2009, 15:33:10) 
>>> class Library(object):
...   def __init__(self):
...     self.books = { 'title' : object, 'title2' : object, 'title3' : object, }
...   def __getitem__(self, i):
...     return self.books[i]
... 
>>> library = Library()
>>> library['title']
<type 'object'>
>>> for book in library:
...   print book
... 
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 5, in __getitem__
KeyError: 0
>>> 

How do I tell it to simply return the object for each item in the dictionary (the key doesn't matter) ?

解決方案

def __iter__(self): return self.books.itervalues()

這篇關于如何使用 __getitem__ 和 __iter__ 并從字典中返回值?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!

【網站聲明】本站部分內容來源于互聯網,旨在幫助大家更快的解決問題,如果有圖片或者內容侵犯了您的權益,請聯系我們刪除處理,感謝您的支持!

相關文檔推薦

Troubles while parsing with python very large xml file(使用 python 解析非常大的 xml 文件時出現問題)
Find all nodes by attribute in XML using Python 2(使用 Python 2 在 XML 中按屬性查找所有節點)
Python - How to parse xml response and store a elements value in a variable?(Python - 如何解析 xml 響應并將元素值存儲在變量中?)
How to get XML tag value in Python(如何在 Python 中獲取 XML 標記值)
How to correctly parse utf-8 xml with ElementTree?(如何使用 ElementTree 正確解析 utf-8 xml?)
Parse XML from URL into python object(將 XML 從 URL 解析為 python 對象)
主站蜘蛛池模板: 中文字幕亚洲精品 | 黄色成人国产 | 久久中文字幕一区 | 欧美精品在线一区 | 中文字幕精品视频 | 免费在线色 | 亚洲欧美成人影院 | 男人天堂网址 | 男女羞羞视频在线 | h视频在线免费 | 国产在线观看网站 | 色吊丝2 | 天天爱天天操 | 天堂中文资源在线 | 国产一区二区三区高清 | 国产无套一区二区三区久久 | 黄色片免费 | 成人3d动漫一区二区三区91 | 超碰av免费 | 成人做爰999 | 91精品国产91久久久久久密臀 | 337p日本欧洲亚洲大胆精蜜臀 | 久热国产在线 | 国产精品乱码一区二区三区 | 天堂av在线影院 | 日本超碰 | 国产一区| 久久精品欧美视频 | 国产精品久久久久久238 | 黄色中文字幕 | 在线看无码的免费网站 | 午夜精品久久久 | 成人午夜黄色 | 久久曰视频| 日韩伦理一区二区 | 久久久久久久久久久久久91 | 欧日韩在线观看 | 久久综合一区 | 日韩av最新网址 | 成人在线观看黄 | 日本在线播放一区二区 |