Saturday 5 December 2015

Python modules

Module is a file, which contains definitions. We can define classes, modules, variables etc., in module file and reuse them in other python scripts.

For example, create a file ‘arithmetic.py’ and copy following code.

arithmetic.py
def sum(a, b):
  return a+b

def subtract(a, b):
  return a-b
  
def mul(a,b):
  return a*b
  
def div(a, b):
  return a/b

Open python interpreter, import the module using ‘import’ key word and call the functions defined in module.    

>>> import arithmetic
>>> 
>>> arithmetic.sum(10, 20)
30
>>> arithmetic.subtract(10, 20)
-10
>>> arithmetic.mul(10, 20)
200
>>> arithmetic.div(10, 20)
0.5


How to get the module name
By using the property ‘__name__’, you can get the module name.
>>> arithmetic.__name__
'arithmetic

Use functions of module as local functions

>>> import arithmetic
>>> sum=arithmetic.sum
>>> sub=arithmetic.subtract
>>> mul=arithmetic.mul
>>> div=arithmetic.div
>>> 
>>> sum(10, 20)
30
>>> mul(10, 20)
200
>>> sub(10, 20)
-10





Previous                                                 Next                                                 Home

No comments:

Post a Comment