def test_fibonacci_generator2(self): ''' Tests fibonacci generator2 ''' fib = fibonacci.Fib(5) list(fib) # exhaust iterator self.assertRaises( StopIteration, fib.__next__) # just passing function, do not execute it
def run(self): if self.__name == FIBONACCI_STRING: for x in fibonacci.Fib( self.__recursions, self.__offset, self.__multiply): # get numbers one by one with generator self.emit(QtCore.SIGNAL('addNumber(int)'), x) if self.__name == PADOVAN_STRING: for x in padovan.pad( self.__recursions, self.__offset, self.__multiply): # get numbers one by one with generator self.emit(QtCore.SIGNAL('addNumber(int)'), x)
reserved word this in C + + or Java, but self is not a reserved word in Python, merely a naming convention. Nonetheless, please don’t call it anything but self; this is a very strong convention. In the __init__() method, self refers to the newly created object; in other class methods, it refers to the instance whose method was called. Although you need to specify self explicitly when defining the method, you do not specify it when calling the method; Python will add it for you automatically. ''' def some_method(self): pass import fibonacci ''' To instantiate a class, simply call the class as if it were a function, passing the arguments that the __init__() method requires. The return value will be the newly created object. ''' fib = fibonacci.Fib(200) print(fib.__doc__) print(fib.__class__) ''' The for loop calls Fib(1000), as shown. This returns an instance of the Fib class. Call this fib_inst. • Secretly, and quite cleverly, the for loop calls iter(fib_inst), which returns an iterator object. Call this fib_iter. In this case, fib_iter == fib_inst, because the __iter__() method returns self, but the for loop doesn’t know (or care) about that. • To “loop through” the iterator, the for loop calls next(fib_iter), which calls the __next__() method on the fib_iter object, which does the next-Fibonacci-number calculations and returns a value. The for loop takes this value and assigns it to n, then executes the body of the for loop for that value of n. • How does the for loop know when to stop? I’m glad you asked! When next(fib_iter) raises a StopIteration exception, the for loop will swallow the exception and gracefully exit. (Any other exception will pass through and be raised as usual.) And where have you seen a StopIteration exception? In the __next__() method, of course!
import fibonacci fib1 = fibonacci.Fib(1000) fib2 = fibonacci.Fib(2000) print(fib1) print("__doc__: ", fib1.__doc__) print('__class__: ', fib1.__class__) print(fib1.max) print(fib2.max)
def test_fibonacci_generator(self): ''' Tests fibonacci generator ''' fib = fibonacci.Fib(10) self.assertEqual(list(fib), [0, 1, 1, 2, 3, 5, 8])