Problem with iterators and inheritance
Scott David Daniels
scott.daniels at acm.org
Mon May 8 13:03:40 EDT 2006
Yves wrote:
(in surprise because C's __init__ doesn't over-ride next)
> class A(object):
> def __init__(self, n): self.n = n
> def __iter__(self): return self
> def next(self):
> if self.n > 0:
> self.n -= 1
> return "A: %d" % self.n
> else: raise StopIteration()
>
> class C(A):
> def __init__(self, n):
> super(C,self).__init__(n)
> self.next = self.mynext
> def __iter__(self): return self
> def mynext(self):
> if self.n > 0:
> self.n -= 1
> return "C: %d" % self.n
> else:
> raise StopIteration()
The answer is to understand the following code:
class Xyz(object):
def __init__(self): self.x = 23
def x(self): return 42
print Xyz().x
New-style classes control object attribute lookups,
and messages go to the class first (ignoring the instance
dictionary). That is also how "properties" work, which
(if you think about it right) could not otherwise survive
the first assignment of the property.
--Scott David Daniels
scott.daniels at acm.org
More information about the Python-list
mailing list