Create your own modules

Source: Internet
Author: User
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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.