+ 2
What's the error?
class FibGenerator: def __next__(self): self.first = 0 self.second = 1 def __iter__(self): return self def __next__(self): fibNum = self.first+self.second self.first=self.second self.second = fibNum return fibNum fib =FibGenerator() for i in range(1,10): print(next(fib)) *This code is giving an error - "Traceback (most recent call last): File "D:/Study/Python/Tutorial/Comprehension/Prog.py", line 15, in <module> print(next(fib)) File "D:/Study/Python/Tutorial/Comprehension/Prog.py", line 8, in __next__ fibNum = self.first+self.second AttributeError: 'FibGenerator' object has no attribute 'first' "* How to solve this error?
3 Respuestas
+ 5
This code runs. I think you want to initialize second to 1 instead of -1 on line 8 also.
https://code.sololearn.com/cozj3wiGqMk5
+ 2
John Wells Yes but he has not defined constructor in code copied in description
+ 1
Your have defined two time __next__ method. and i think that first one its the ctor of FibGenerator class