Tuesday, April 10, 2012

More On Modules

Hello Everyone, in this post, I Will Discuss something more about Modules, its very interesting, so lets get started.

So far we know what a Module is and how to use them. But as We know that Modules are created by Python Users, for some specific outputs or results. Well If I make a Module and use it in my programs, I am aware of the functions in that Module. But if I use a Module created by someone else or rather the Python Builtin Modules, how am I supposed to know what are the functions of the Modules. And what does the Module do.

Well lets create a Module and try to understand with the example. The Same applies for any other Module that you will come across in Your Python Life.

Lets create a Module:

#SimpleMath Module
def __doc__():
    print "This is a simple Math Module Which Can Add Or Subtract"
def add(x,y):
    z = x + y
    return z
def sub(x,y):
    z = x - y
    return z

Save it as simplemath.py under C:/python27

Now On the Python Shell, what can you to do understand the Module,

>>> import simplemath
>>> #First we need to import the Module and then proceed
>>> dir(simplemath)
['__builtins__', '__doc__', '__file__', '__name__', '__package__', 'add', 'sub']
>>> #dir(modulename) --> Lists the functions and variable name used in the Module
>>> help(simplemath)
Help on module simplemath:

NAME
    simplemath - #SimpleMath Module

FILE
    c:\python27\simplemath.py

FUNCTIONS
    add(x, y)
   
    sub(x, y)


>>> #help(modulename) - returns a detailed report of the Module
>>> help(simplemath.add)
Help on function add in module simplemath:

add(x, y)

>>> #help(modulename.functionname) -->displays the specific report of the function
>>> simplemath.__doc__()
This is a simple Math Module Which Can Add Or Subtract
>>> #modulename.__doc__() --> found on almost all standard Module, which returns a short description about what the Module does.

Well This was just a simple Module that I created for explanation, there exists a Huge Library Of Modules. And to understand any Module these steps helps every-time.

Few Builtin Modules that you would Like To Practice with are: math, urllib, urllib2, system, etc

Check them out, and try to understand them as Modules are used heavily in Python Scripts.

Thank You and Don't Forget to check My Next Post.

0 comments:

Post a Comment