I am studying python with the book Beginning Python: From Novice to Professional, and I get confused about the section discussing iterators. There is an example in this section:
>>> Class Fibs:
... def __init__(self):
... self.a = 0
... self.b = 1
... def __next__(self):
... self.a, self.b = self.b, self.a + self.b
... return self.a
... def __iter__(self):
... return self
...
>>> fibs = Fibs()
>>> for f in fibs:
... if f > 1000:
... print(f)
... break
...
1597
To be honest, I only know that fibs is an object with methods __next__ and __iter__, but have no idea about what happens in each step of the loop. And I made a test:
>>> isinstance(f, Fibs)
False
>>> f is fibs
False
>>> isinstance(f, int)
True
>>> fibs.a
1597
This makes me much more confused! Why the boolean value of f is fibs is False? And why fibs.a become 1597 after the execution of the loop?(Is the method __next__ automatically called in the loop?) Thanks in advance.
print(f)wouldn't give you1597. And you couldn't dof > 1000iffwasn't an integer.