Python by Swaroop C H - HTML preview

PLEASE NOTE: This is an HTML preview only and some elements such as links or page numbers may be incorrect.
Download the book in PDF, ePub, Kindle for a complete version.

Creating your own Modules

Example 8.3. How to create your own module

#!/usr/bin/python
# Filename: mymodule.py
def sayhi():
print 'Hi, this is mymodule speaking.' version = '0.1'
# End of mymodule.py

 

The above was a sample module. As you can see, there is nothing particularly special about compared to our usual Python program. We will next see how to use this module in our other Python programs. Remember that the module should be placed in the same directory as the program that we import it in, or the module should be in one of the directories listed insys.path .

 

#!/usr/bin/python
# Filename: mymodule_demo.py import mymodule
mymodule.sayhi()
print 'Version', mymodule.version

Output

$ python mymodule_demo.py Hi, this is mymodule speaking. Version 0.1

How It Works

Notice that we use the same dotted notation to access members of the module. Python makes good reuse of the same notation to give the distinctive 'Pythonic' feel to it so that we don't have to keep learning new ways to do things.