473,386 Members | 1,958 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,386 software developers and data experts.

Problem with iterators and inheritance

Hi!

I was fiddling around a bit with iterators and I came across some
strange behaviour. I have the following simple code:

--
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 B(A):
def __init__(self, n):
super(B,self).__init__(n)

def __iter__(self):
return self

def next(self):
if self.n > 0:
self.n -= 1
return "B: %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()
if __name__=='__main__':
a = A(2)
b = B(2)
c = C(2)
for k in [a,b,c]:
# Iterate over the object
for i in k:
print i
print "="*50

--

The output I expected was

A: 1
A: 0
==================================================
B: 1
B: 0
==================================================
C: 1
C: 0
==================================================
but strangely enough I ended up with

A: 1
A: 0
==================================================
B: 1
B: 0
==================================================
A: 1
A: 0
==================================================
Or in other words, it appears that Python does not use 'mynext' when
iterating over an object of class C. When I call c.next() directly
though, it does execute the code from the 'mynext' method. In my
understanding, iterating over a list, simply consists of repeatedly
calling the next() function until a StopIteration is raised, so there
should not really be any difference.
Another thing I noticed is that if I do not let A inherit from 'object'
(removing the calls to super(..) and adding appropriate initalization of
self.n), the result is as expected.
I am completely puzzled, so if anybody could shed some light on this,
I'd appreciate this.

YVES
May 8 '06 #1
1 1454
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
sc***********@acm.org
May 8 '06 #2

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

45
by: Joh | last post by:
hello, i'm trying to understand how i could build following consecutive sets from a root one using generator : l = would like to produce : , , , ,
8
by: babak | last post by:
Hi everyone I have a problem with Iterators and containers in STL that hopefully someone can help me with. This is what I try to do: I have an associative (map) container and I have a...
15
by: fungus | last post by:
I'm moving some code from VC++ 6 to VC++ 2005 and I've run into a nasty problem because iterators are no longer pointers. In the program I'm moving, there's a std::vector of items hidden inside...
19
by: fungus | last post by:
I mentioned earlier to day that I was moving some code from VC++6 to VC++2005 and having trouble with the new iterators. There's all sorts of problems cropping up in the code thanks to this...
6
by: gexarchakos | last post by:
Hi there, Please give me at least a hint... I have a problem implementing a function object with parameters two iterators. That is: A class 'node' produces messages using a routing policy....
18
by: desktop | last post by:
1) I have this code: std::list<intmylist; mylist.push_back(1); mylist.push_back(2); mylist.push_back(3); mylist.push_back(4);
3
by: Jess | last post by:
Hello, Iterators are typically put into five different categories, namely input iterator, output iterator, forward iterator, bidirectional iterator and random iterator. The differences come...
4
by: conrad | last post by:
I was reading about iterators and how they are used with containers provided by the STL. They seem like aliases for pointer types. Is this the case? What's the benefit of doing it this way, if...
11
by: Juha Nieminen | last post by:
Assume we have this: std::list<Typelist1(10, 1), list2(20, 2); std::list<Type>::iterator iter = list1.end(); list1.swap(list2); What happens here, according to the standard? 1) 'iter'...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.