Page 444 - CITS - Computer Software Application -TT
P. 444

COMPUTER SOFTWARE APPLICATION - CITS




           Looping Through an Iterator
           We can also use a for loop to iterate through an iterable object:
           Create an Iterator
           To create an object/class as an iterator you have to implement the methods __iter__() and __next__() to your
           object.
           As you have learned in the Python Classes/Objects chapter, all classes have a function called __init__(), which
           allows you to do some initializing when the object is being created.

           The __iter__() method acts similar, you can do operations (initializing etc.), but must always return the iterator
           object itself.
           The __next__() method also allows you to do operations, and must return the next item in the sequence.

           Example
           Create an iterator that  returns numbers, starting with 1,  and each sequence will increase by one (returning
           1,2,3,4,5 etc.):

           class MyNumbers:
             def __iter__(self):
               self.a = 1
               return self

             def __next__(self):
               x = self.a
               self.a += 1

               return x
           myclass = MyNumbers()
           myiter = iter(myclass)

           print(next(myiter))
           print(next(myiter))
           print(next(myiter))

           print(next(myiter))
           print(next(myiter))


           Python Modules

           Create a Module
           To create a module just save the code you want in a file with the file extension .py:
           Python Modules
           In this tutorial, we will explain how to construct and import custom Python modules. Additionally, we may import
           or integrate Python’s built-in modules via various methods.
           What is Modular Programming?
           Modular programming  is the practice of  segmenting a single, complicated coding task  into multiple, simpler,
           easier-to-manage sub-tasks. We call these subtasks modules. Therefore, we can build a bigger program by
           assembling different modules that act like building blocks.
           Modularizing our code in a big application has a lot of benefits.





                                                           431

 CITS : IT&ITES - Computer Software Application - Lesson 120 - 137  CITS : IT&ITES - Computer Software Application - Lesson 120 - 137
   439   440   441   442   443   444   445   446   447   448   449