+ 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?

4th Jun 2018, 7:27 PM
Agnibha Chakraborty
Agnibha Chakraborty - avatar
3 ответов
+ 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
4th Jun 2018, 7:43 PM
John Wells
John Wells - avatar
+ 2
John Wells Yes but he has not defined constructor in code copied in description
4th Jun 2018, 7:45 PM
KrOW
KrOW - avatar
+ 1
Your have defined two time __next__ method. and i think that first one its the ctor of FibGenerator class
4th Jun 2018, 7:36 PM
KrOW
KrOW - avatar