I am new to python and object-oriented programing.
Why use iterator classes vs iterative variable?
Is the way class (object-oriented) just more modular?
iterative example:
for i in n:
i = i +1
print("Hi ", i)
I am new to python and object-oriented programing.
Why use iterator classes vs iterative variable?
Is the way class (object-oriented) just more modular?
iterative example:
for i in n:
i = i +1
print("Hi ", i)
I am new to python and object-oriented programing.
Why use iterator classes vs iterative variable?
I’m not sure I understand this question.
Is the way class (object-oriented) just more modular?
iterative example:
for i in n:
i = i +1
print("Hi ", i)
This is very odd. What is in “n”? A list? What does the “i = i + 1” do?
A class is for implementing things. If you’ve already got an iterator,
or some iterable thing like a list, you don’t need to implement a new
class. You’d write a class if you needed to make some special kind of
iterator not already available.
If this doesn’t help you, can you:
Some terminology:
an iterable: something with a iter method, which returns an
iterator
an iterator: something with a next method, which returns the next
value in the series of values
An iterable class defines one method: iter to return an iterator
over whatever the class instance embodies.
An iterator has a next method to return the next value in the
iteration, and usually also an iter which returns itself.
Often people just define iter as a generator function, which
automatically returns a generator object which has these methods:
class RangeLike:
def __init__(self, value):
self.value = value
def __iter__(self):
for i in range(self.value):
yield i
This is a simple class which just stores a number and when you iterate
over it, yields values 0…(value-1) inclusively, like this:
R = RangeLike(4)
for i in R:
print(i)
The for-loop calls “iter(R)” to obtain an iterator for R, and that is a
generator function. It looks like a regular function, but instead of
returning a single value it "yield"s multiple values. Calling it gets
you a “generator object”, which is an iterator (something which yields a
series of values).
The mechanism of the for-loop looks like this:
R = RangeLike(4)
R_iter = iter(R)
while True:
try:
i = next(R_iter)
except StopIteration:
break
print(i)
So the for-loop calls iter(R), getting an iterator we keep as “R_iter”;
that calls R.iter() to get that iterator.
Then the loop itself calls next(R_iter) to get the next value for “i”;
each such call calls R_iter.next().
When R_iter came from a generator function, that runs the function until
it issues a “yield” command. Then next time you call next(), the
function continues running until it again issues a “yield” command.
Cheers,
Cameron Simpson cs@cskk.id.au