次の例が機能しない理由を理解しようとしています。
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 0x7fb2af7d1c90>
[<__main__.DerivedNO object at 0x7fb2af7d1c90>]
<__main__.DerivedO object at 0x7fb2af7d1d10>
Traceback (most recent call last):
File "playground.py", line 41, in <module>
print list(y)
File "playground.py", line 11, in next
if self.count:
AttributeError: 'DerivedO' object has no attribute 'count'
ご覧のとおり、でメソッドDerivedO
を割り当てようとしても、新しいメソッドは上書きされません。何故ですか?nextへの単純な呼び出しは正常に機能しますが、反復手法を使用する場合はまったく機能しません。next()
__init__
編集:私の質問が完全に明確ではなかったことに気づきました。AttributeErrorは、私が解決しようとしている問題ではありません。しかし、それは私が思っていたようにオンnext()
ではBaseClass
なく、オンになっていることを示しています。DerivedO