# -*- coding: utf-8 -*- class Library(object): def __init__(self): self.books = { 'title' : 'a', 'title2' : 'b', 'title3' : 'c', } def __getitem__(self, i): return self.books[i] def __iter__(self): # 方法1 使用生成器 for titles in self.books: yield self.books[titles] # 方法2 使用迭代器 # return self.books.itervalues() library = Library() # 1.普通方法 print library.books['title'] # 2.使用__getitem__ print library['title'] # 3.迭代器 for book in library: print book
问题:那__getitem__可以替代__iter__方法吗
1.list
# -*- coding: utf-8 -*- class Library(object): def __init__(self): self.books = [ 'title' , 'a', 'title2' , 'b', 'title3' , 'c', ] def __getitem__(self, i): return self.books[i] # def __iter__(self): # 方法1 使用生成器 # for titles in self.books: # yield self.books[titles] # 方法2 使用迭代器 # return self.books.itervalues() library = Library() # 1.普通方法 print(library.books[1]) # 2.使用__getitem__ print(library[1]) # 3.迭代器 for book in library: print(book)
结果为
>>>
===================== RESTART: C:/Users/CUI/Desktop/1.py =====================
a
a
title
a
title2
b
title3
c
>>>
2.dict
# -*- coding: utf-8 -*- class Library(object): def __init__(self): self.books = { 'title' : 'a', 'title2' : 'b', 'title3' : 'c', } def __getitem__(self, i): return self.books[i] # def __iter__(self): # 方法1 使用生成器 # for titles in self.books: # yield self.books[titles] # 方法2 使用迭代器 # return self.books.itervalues() library = Library() # 1.普通方法 print(library.books[1]) # 2.使用__getitem__ print(library[1]) # 3.迭代器 for book in library: print(book)
结果为:
>>> ===================== RESTART: C:/Users/CUI/Desktop/1.py ===================== Traceback (most recent call last): File "C:/Users/CUI/Desktop/1.py", line 20, in <module> print(library.books[1]) KeyError: 1 >>>
结论:当字段为索引行数据类型(如:list, tuple,str)时,可以替换,当字段为hash型类型(如dict,set)时,不能替换。