Python (27): module

Source: Internet
Author: User
Tags python script

First, Module introduction 1. Modules in Python

A friend with C programming experience knows that if you want to refer to the SQRT function in C, you must use the phrase # include <math.h> introduce the MATH.H header file, otherwise it cannot be called normally.

So in Python, what if you want to refer to some other function?

There is a concept in Python called module, which is similar to a header file in C and a package in Java, such as calling the SQRT function in Python, which must be introduced into the math module with the Import keyword. Here's a look at the modules in Python.

The popular point: The module is like a toolkit, to use the tool in the toolkit (like a function), you need to import this module

2.import

Using the keyword import in Python to introduce a module, such as referencing module math, can be introduced with import math at the very beginning of the file.

Shaped like:

import module1,mudule2...

When the interpreter encounters an import statement, the module is imported if it is in the current search path.

When you call a function in the math module, you must refer to this:

  模块名.函数名

Because a function with the same name is in more than one module, the interpreter cannot know exactly which function to invoke if it is only called by the function name. So if the module is introduced as described above, the calling function must add the module name

    import math    #这样会报错    print sqrt(2)    #这样才能正确输出结果    print math.sqrt(2)

Sometimes we just need to use a function in the module, just to introduce the function, which can be implemented in the following way:

from 模块名 import 函数名1,函数名2....

Not only can we introduce functions, but we can also introduce some global variables, classes, etc.

Attention:

when introduced in this way, only the function name can be given when the function is called, and the module name cannot be given, but when the two modules contain the same name function, the subsequent introduction overwrites the previous one. in other words, if the function function () is in module A, there is also functional function () in module B, and if you introduce the functions in the first and B functions in a, then when you call function, is to execute the function functions in module B.

If you want to introduce everything in math at once, you can also use the From math import * to implement

3.from...import

The FROM statement of Python lets you import a specified part from the module into the current namespace

The syntax is as follows:

 from modname import name1[, name2[, ... nameN]]

For example, to import the Fibonacci function of a module FIB, use the following statement:

from fib import fibonacci

Attention:

The entire FIB module will not be imported into the current namespace, it will only introduce the Fibonacci individual in the FIB

4.from ... import *

It is also possible to import all the contents of a module into the current namespace, just use the following declaration:

from modname import *

Attention:

This provides an easy way to import all the items in a module. However, such statements should not be used too much.

5. As
    In [1]: import time as tt    In [2]: time.sleep(1)    ---------------------------------------------------------------------------    NameError                                 Traceback (most recent call last)    <ipython-input-2-07a34f5b1e42> in <module>()    ----> 1 time.sleep(1)    NameError: name ‘time‘ is not defined    In [3]:     In [3]:     In [3]: tt.sleep(1)    In [4]:     In [4]:     In [4]: from time import sleep as sp    In [5]: sleep(1)    ---------------------------------------------------------------------------    NameError                                 Traceback (most recent call last)    <ipython-input-5-82e5c2913b44> in <module>()    ----> 1 sleep(1)    NameError: name ‘sleep‘ is not defined    In [6]:     In [6]:     In [6]: sp(1)    In [7]:

6. Positioning module

When you import a module, the Python parser searches the module location for the current directory, and if it is not in the current directory, Python searches for each directory under the shell variable Pythonpath, and Python looks at the default path if it is not found. Under UNIX, the default path is generally/usr/local/lib/python/.

The module search path is stored in the Sys.path variable of the system module. The variable contains the current directory, Pythonpath, and the default directory determined by the installation process.

Second, the module production 1. Define your own module

In Python, each Python file can be used as a module whose name is the name of the file.

For example, there is a file test.py that defines the function add in test.py:

#test.pydef add(a,b):    return a+b

2. Call the module of your own definition

In other files, you can import test first, then call through Test.add (A, B), and of course, through the From test import add to introduce

    #main.py        import test    result = test.add(11,22)    print(result)

3. Test module

In practice, when a developer finishes writing a module, in order for the module to achieve the desired effect in the project, the developer will add some test information to the Py file itself, for example:

    #test.py    def add(a,b):        return a+b    # 用来进行测试    ret = add(12,22)    print(‘int test.py file,,,,12+22=%d‘%ret)

If you introduce this file in another py file, think about whether the code that you are testing will also be executed!

    #main.py    import test    result = test.add(11,22)    print(result)

At this point, you can find the test code in test.py, should be executed when the test.py file is executed separately, should not be referenced in other files and executed

To solve this problem, Python has a variable __name__ when executing a file. Can be judged according to the results of the __name__ variable, is the direct execution of the Python script or is introduced to execute, so as to be able to selectively execute the test code

Iv. Package 1 in Python. Introduction Package

The package organizes the associated modules together, put them in the same folder, and creates a name for the __init__.py file in this folder, then this folder is called the package. This effectively avoids the problem of module name collisions and makes the application organizational structure clearer.

2. __init__.py file

__init__.py controls the import behavior of the package.

__init__.py is empty, simply importing the package, not importing the modules in the package.

You can write content in the __init__.py file, which is executed when you import it.

3.__all__

In the __init__.py file, define a __all__ variable that controls the module imported from the package name import *. If there is a __all__ variable in a file, it means that the element in the variable will not be imported from XXX import *.

4. Extensions: Nested packages

Let's assume that our package example has the following directory structure:

Phone/    __init__.py    common_util.py    Voicedta/        __init__.py        Pots.py        Isdn.py    Fax/        __init__.py        G3.py    Mobile/        __init__.py        Analog.py        igital.py    Pager/        __init__.py        Numeric.py

The Phone is the topmost package, VOICEDTA, etc. is its child package. We can import the child packages like this (you can also use From-import to implement different requirements for importing):

import Phone.Mobile.AnalogPhone.Mobile.Analog.dial()

The first approach is to import only the top-level child package, and then use the attribute/point operator to reference the sub-Baoshu:

from Phone import MobileMobile.Analog.dial(‘555-1212‘)

In addition, we can also refer to more sub-packages:

from Phone.Mobile import AnalogAnalog.dial(‘555-1212‘)

In fact, you can always import along the sub-package's tree structure:

from Phone.Mobile.Analog import dialdial(‘555-1212‘)

In our directory structure above, we can find a lot of __init__.py files. These are initialization modules that need to be used when the From-import statement imports a child package. If they are not used, they can be empty files.

The package also supports the From-import all statement:

from package.module import *

However, such a statement will import which files depend on the filesystem of the operating system. So we add the __all__ variable to the __init__.py. The variable contains the name of the module that should be imported when executing such a statement. It consists of a list of module name strings:

Five, module release 1.MYMODULE directory structure as follows:
.├── setup.py├── suba│   ├── aa.py│   ├── bb.py│   └── __init__.py└── subb    ├── cc.py    ├── dd.py    └── __init__.py
2. Edit the setup.py file

Py_modules you need to indicate which py file you want to include

from distutils.core import setupsetup(name="dongGe", version="1.0", description="dongGe‘s module", author="dongGe", py_modules=[‘suba.aa‘, ‘suba.bb‘, ‘subb.cc‘, ‘subb.dd‘])
3. Building the module
python setup.py build

Post-build directory structure:

.├── build│   └── lib.linux-i686-2.7│       ├── suba│       │   ├── aa.py│       │   ├── bb.py│       │   └── __init__.py│       └── subb│           ├── cc.py│           ├── dd.py│           └── __init__.py├── setup.py├── suba│   ├── aa.py│   ├── bb.py│   └── __init__.py└── subb    ├── cc.py    ├── dd.py    └── __init__.py
4. Generate a Release archive package
python setup.py sdist

After packaging, generate the final release Zip package dongge-1.0.tar.gz, directory structure:

.├── build│   └── lib.linux-i686-2.7│       ├── suba│       │   ├── aa.py│       │   ├── bb.py│       │   └── __init__.py│       └── subb│           ├── cc.py│           ├── dd.py│           └── __init__.py├── dist│   └── dongGe-1.0.tar.gz├── MANIFEST├── setup.py├── suba│   ├── aa.py│   ├── bb.py│   └── __init__.py└── subb    ├── cc.py    ├── dd.py    └── __init__.py

Vi. installation and use of modules 1. How to Install

In command-line mode, locate the module's tarball, unzip it, go to the folder, execute the command python setup.py install.

Note: If you perform a directory installation at install time, you can use the Python setup.py install--prefix= installation path

2. Introduction of Modules

In the program, use the from import to complete the installation of the module

from 模块名 import 模块名或者*

Python (27): module

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.