以下程序的目的是学习python生成器和迭代器实现,以便了解Python魔术方法。
我无法实现iteritems()
功能。另外,我想知道我是否朝着正确的方向前进,或者在理解python魔术方法时我在概念上是错误的。
import random
class Random(object):
""" generate randomised int of specified length --> [r1, r2, r3....] """
def __init__(self, length = 1, rand_range = 100):
self.index = 0
self.generated_range = []
self.length = length if str(length).isdigit() else 1
self.rand_range = rand_range if str(rand_range).isdigit() else 100
def __iter__(self): return self
def next(self):
if self.index < self.length:
item = random.randrange(0, self.rand_range)
self.generated_range.append(item)
self.index += 1
return item
raise StopIteration
def __eq__(self, obj):
if self.length == obj.length and self.rand_range == obj.rand_range:
return True
return False
def __len__(self):
return self.length
def __contains__(self, item):
if not self.index == self.length:
while self.next(): continue
if item in self.generated_range:
return True
return False
def __getitem__(self, key):
if key in self.generated_range:
return key * 100
raise KeyError
def __setitem__(self, key, value):
raise NotImplemented
def __delitem__(self, key):
raise NotImplemented
def iteritems(self):
if not self.index == self.length:
while self.next(): continue
for item in self.generated_range:
yield item
if __name__ == '__main__':
r1 = Random(10)
print [ r for r in r1]
print 10 in r1
r2 = Random(20)
print r2.iteritems()
答案 0 :(得分:4)
iteritems应该为字典返回一系列(key,val)对,所以我认为它不适合你的班级。如果您创建了UserDict的后代,则可能存在覆盖它的情况。
如果你覆盖了iteritems,你应该通过产生键值组来实现。
糟糕的程序员覆盖:
def iteritems(self):
return iter([(x[0], x) for x in "alpha bravo charlie".split()])