Python Iterator - For I In [something]
Solution 1:
Question 1) - What does for items in b mean? what is it referring to? what is in b?
This is documented:
- https://docs.python.org/3/tutorial/controlflow.html#for-statements
- https://docs.python.org/3/reference/compound_stmts.html#the-for-statement
- https://docs.python.org/3/library/stdtypes.html#iterator-types
Question 2) - Assuming it refers to the the three items we added to it. Why does it go on infine loop stuck on: The potato weighs 2 kg and Not going to the other 2 elements? (It works fine if I increment )
Because if you don't increment the index, it's never greater than len(self.volume)
, so your iterator always yields the same object and never raises StopIteration
.
EDIT
shouldn't it be 'for i in b.volume' as we added items in volume variable not in 'b'?
Well, the point of making Box
an iterable (and an iterator) is actually to hide how Item
s are stored (law of demeter)- note how the client code uses Box.add_item()
, not Box.volume.append()
.
The current implementation is faulty though as it exposes .volume
and index
as part of the public API when they should be protected (names prefixed with a single leading underscore, which is the Python convention for "protected" attributes), and it's possibly a bit incomplete too (it should at least expose a way to know if the box is empty / how many items it contains).
Post a Comment for "Python Iterator - For I In [something]"