| Concise Python tutorial |
| Chapter 4 modules |
| Previous Page |
Create your own modules |
Next Page |
Create your own modules
Creating your own modules is very simple. You have been doing this all the time! Each Python program is also a module. You have made sure that it has.pyExtension. The following example will make it clearer.
Create your own module
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
(Source file: code/mymodule. py)
The above isModule. As you can see, it is nothing special than our common Python program. Next we will look at how to use this module in other Python programs.
Remember that this module should be placed in the same directory of the program we entered it, or insys.pathOne of the listed directories.
#!/usr/bin/python
# Filename: mymodule_demo.py
import mymodule
mymodule.sayhi()
print 'Version', mymodule.version
(Source file: code/mymodule_demo.py)
Output
$ python mymodule_demo.py
Hi, this is mymodule speaking.
Version 0.1
How it works
Note that we use the same vertex number to use the module members. Python makes good use of the same mark, so that we Python programmers do not need to constantly learn new methods.
From .. Import
Below is a usagefrom..importSyntax version.
#!/usr/bin/python
# Filename: mymodule_demo2.py
from mymodule import
sayhi, version
# Alternative:
# from mymodule import *
sayhi()
print 'Version', version
(Source file: code/mymodule_demo2.py)
mymodule_demo2.pyOutput andmymodule_demo.pyIdentical.
| Previous Page |
Level 1 |
Next Page |
| Module _ name __ |
Homepage |
Dir () function |