我有一种情况,类外部的for循环似乎正在与类中的枚举交互。
示例代码:
class MyContainerClass(object):
def __init__(self):
self.collection = []
def __str__(self):
return (len(self.collection) == 0 and 'Empty' or
', '.join(str(item) for item in self.collection))
def __iadd__(self,item):
print "adding {item}".format(item=str(item))
self.collection.append(item)
return self
def __iter__(self):
return iter(self.collection)
def discard(self,item):
print "discarding {item}".format(item=str(item))
for index, value in enumerate(self.collection):
if value == item:
print "found {value}=={item}".format(value=value,item=item)
return self.collection.pop(index)
return False
class MyItemClass(object):
def __init__(self,value):
self.value=value
def __str__(self):
return '{value}'.format(value=self.value)
def __eq__(self,other):
if self.value == other.value:
return True
else:
return False
c1 = MyContainerClass()
c2 = MyContainerClass()
c2 += MyItemClass('item1')
c2 += MyItemClass('item2')
c2 += MyItemClass('item3')
c2 += MyItemClass('item4')
c2 += MyItemClass('item5')
print "c1 is : {c1}".format(c1=str(c1))
print "c2 is : {c2}".format(c2=str(c2))
for item in c2:
print "for got {item}".format(item=str(item))
c1 += c2.discard(item)
print "c1 is : {c1}".format(c1=str(c1))
print "c2 is : {c2}".format(c2=str(c2))
生成此输出:
^{pr2}$我相信这是非常明显的,可能与iter函数有关,但我目前看不到。
您正在修改
c2.collection
(在discard
)的同时对其进行迭代(for item in c2:
)。别那样做。在在迭代容器时修改它是不安全的。在
在本例中,所发生的是迭代只是跟踪经过的元素的数量。所以当你取出item1时,迭代器知道它已经超过了容器中的第一个项。。。现在是
item2
。因此,它愉快地继续item3
。在相关问题 更多 >
编程相关推荐