Python Learning Note 4: Modules

Source: Internet
Author: User

Well the national day seven days good recharge it? A variety of wandering, tired of wood has ah ... Look back, seven days what nothing to do, and then look at the purse June, ah, wallet June you starved, I am ...

After the gossip, take a look at the modules in Python now!

First put the code:

main.py:
Import Modulemodule.function ()

module.py:
def function ():    print "Execute function"



An Introduction module
As you can see, we introduce the module in the form of Import module name (no file suffix required).



Two Call methods
Once the module is introduced, the introduced module can be used as an object, and then the module object is used to invoke one of the objects, the format: "Module. Object".



Three introduced module renaming
Modify the main.py as follows:
Import module as Mm.function ()



Four introduces the specified object in the module
Modify the main.py as follows:

From module import functionfunction ()

All objects in the module are introduced: from module import *

Five Search paths
1 folder where the program is located
2 Standard library installation path
3 environment variable Pythonpath path


Six Module Package
We can talk about functionally similar functions in a folder, forming a module package.
However, the folder must contain a __init__.py file that reminds Python that the folder is a module package. __init__.py can be an empty file.


For example: In the folder Dir, there are two function files add.py and sub.py, of course there is a __init__.py, then we can use the following methods to introduce:
Import Dir.add
Import Dir.sub

Finally, put the code on.
__init__.py:
# is empty

test.py:
From Dir.add import addfrom dir.sub import subprint Add (2,1) print sub (2,1)

add.py:
def add (A, B):    return a + b

sub.py:

Def sub (A, b): Return a-a    


Python Learning Note 4: Modules

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.