我试图弄清楚以下示例为什么行不通.
class BaseClass(object):
def __init__(self):
self.count = 1
def __iter__(self):
return self
def next(self):
if self.count:
self.count -= 1
return self
else:
raise StopIteration
class DerivedNO(BaseClass):
pass
class DerivedO(BaseClass):
def __init__(self):
self.new_count = 2
self.next = self.new_next
def new_next(self):
if self.new_count:
self.new_count -= 1
return None
else:
raise StopIteration
x = DerivedNO()
y = DerivedO()
print x
print list(x)
print y
print list(y)
这是输出:
[<__main__.derivedno object at>]
Traceback (most recent call last):
File "playground.py", line 41, in
print list(y)
File "playground.py", line 11, in next
if self.count:
AttributeError: 'DerivedO' object has no attribute 'count'
如您所见,当我尝试在__init__中分配next()方法时,新方法将不会在DerivedO中被覆盖.这是为什么?一个简单的next调用可以很好地工作,但是在使用迭代技术时根本无法工作.
编辑:我意识到我的问题还不完全清楚. AttributeError不是我要解决的问题.但这确实表明next()是在BaseClass上调用的,而不是像我认为的那样在DerivedO上调用的.