Basic Python Tutorial _ Learning Note 12: Charging time-module

Source: Internet
Author: User
Tags shallow copy pprint

Charging Time-module

the standard installation of Python consists of a set of modules, called Standard libraries .

Module

>>> Import Math

>>> Math.sin (0)

0.0

Module is a program

Whatever python program is capable of being imported as a module.

$ cat hello.py

#!/usr/bin/python

Print "hello,signjing!"

$./hello.py

hello,signjing!

If you save the Python program in the /home/ggz2/magiccube/mysh/pys folder, run the following code:

>>> Import Sys

>>> sys.path.append('/home/ggz2/magiccube/mysh/pys ')

All you have to do is tell the interpreter: In addition to looking for the default folder, you need to find the module from the folder /home/ggz2/magiccube/mysh/pys .

After this step, you are ready to import your own modules:

>>> Import Hello

hello,signjing!

Note: When importing the module. You may see a new file appear, in this case /home/ggz2/magiccube/mysh/pys/hello.pyc .pyc python . Span style= "font-family: Arial" > files that can be processed more efficiently. assumes that the same module is imported later, python .pyc file instead of .py file. Unless .py files have changed-in such cases, A new .pyc file is generated.

Deleting a . PYC file does not harm the program (only the equivalent . py file exists)--a new . PYc file is created when necessary.

As you can see. At the time of importing the module. The code is then run. Just import the module again. Nothing would have happened.

>>> Import Hello

>>>

Because importing a module does not mean that some operations are run at import time.

They are primarily used for definitions.

In addition, because only need to define these things once, the import module multiple times and the effect of import is the same.

Module is used to define

The module is run when the program is first imported.

It seems a bit useful--but not very practical. The real use is that they (like classes) can maintain their scope. This means that all defined classes and functions, as well as the assigned variables, are the properties of the module.

Defining functions in a module

$ cat hello2.py

#!/usr/bin/python

def hello ():

Print "Morning,signjing"

>>> Import Hello2

>>> Hello2.hello ()

Morning,signjing

The same method can be used to use whatever name is defined in the global scope of the module.

To make the code reusable, please modularize it!

Add a test code to the module

Modules are used to define functions, classes, and some other content. But there are times when (in fact, often). It is very practical to include some test code that checks whether the module itself is working properly in the module.

$ cat hello3.py

#!/usr/bin/python

def hello ():

Print "Hello!"

# a Test

Hello ()

>>> Import Hello3

Hello!

>>> Hello3.hello ()

Hello!

The key to avoiding such a situation is whether the "tell" module itself is executed as a program or imported into another program. In order to achieve this. You need to use the __name__(double underscore) variable:

>>> __name__

' __main__ '

>>> hello3.__name__

' Hello3 '

Visible. In the main program (including the interpreter's interactive prompt). the value of the variable __name__ is '__main__'. Instead, in the imported module. This value is set to the name of the module. so. In order to make the module's test code more useful, it can be placed in an if statement:

$ cat hello4.py

#!/usr/bin/python

def hello ():

print "Hello"

def test ():

Hello ()

If __name__== ' __main__ ': Test ()

>>> Import Hello4

>>>

>>> Hello4.hello ()

Hello

Make your module available to place the module in the correct location

It is very easy to put your module in the right place (or in the right place). Just find out where the Python interpreter is looking for the module. Then you can put your own files there.

Linux Systems:

>>> Import Sys,pprint

>>> pprint.pprint(Sys.path)

[‘‘,

'/usr/lib64/python26.zip ',

'/usr/lib64/python2.6 ',

'/usr/lib64/python2.6/plat-linux2 ',

'/usr/lib64/python2.6/lib-tk ',

'/usr/lib64/python2.6/lib-old ',

'/usr/lib64/python2.6/lib-dynload ',

'/usr/lib64/python2.6/site-packages ',

'/usr/lib64/python2.6/site-packages/gtk-2.0 ',

'/usr/lib/python2.6/site-packages ']

Windows System:

>>> Import Sys,pprint

>>> Pprint.pprint (Sys.path)

[‘‘,

' D:\\software (x86) \\Python27\\Lib\\idlelib ',

' C:\\windows\\system32\\python27.zip ',

' D:\\software (x86) \\Python27\\DLLs ',

' D:\\software (x86) \\Python27\\lib ',

' D:\\software (x86) \\Python27\\lib\\plat-win ',

' D:\\software (x86) \\PYTHON27\\LIB\\LIB-TK ',

' D:\\software (x86) \\Python27 ',

' D:\\software (x86) \\Python27\\lib\\site-packages ']

Each string provides a folder in which to place the module. The interpreter is able to find the required modules from these folders. Although these folders are available. But the site-packages folder is the best choice, because it is used to do these things.

Create a file under D:\\software (x86) \\Python27\\lib\\site-packages in the Windows operating system another_hello.py:

def hello ():

Print "hello,win7"

>>> Import Another_hello

>>> Another_hello.hello ()

Hello,win7

Visible. Just put the module in a folder like Site-packages, and all the programs will be able to import it.

Tell the compiler where to look.

"Place modules in the right place" This workaround may not apply in the following cases:

1) Do not want to fill your module with the python interpreter folder;

2) There is no permission to store files in the Python interpreter folder.

3) Want to place the module somewhere else

In that case, tell the interpreter where to look. The Sys.pathmentioned earlier. But this is not a generic approach. The standard implementation method is to include the folder where the module resides in the PYTHONPATH environment variable.

The contents of the PYTHONPATH environment variable vary depending on the operating system used, but basically. It's very similar to Sys.path-a folder list.

Environment Variables are not part of the Python interpreter. They are part of the operating system.

Tip: You do not need to use PYTHONPATH to change sys.path.

The path configuration file provides a practical shortcut. Allows python to complete the work for you. A path profile is a file with a . PTH extension that contains the folder information that should be added to the sys.path . Blank lines and lines beginning with # are ignored.

files that begin with import are run. For Windows , use the folder name defined by Sys.prefix; in Unix and mac OSX The Site-packages folder is used in the .

naming modules

The file that includes the module code is the same as the module name-plus the . py extension.

In Windows systems, you can also use the . pyw extension.

Package

To organize modules, you can group them into packages. Packages are basically another class of modules.

The interesting thing is that they can all include other modules.

When the module is stored in a file (with a . pyextension), the package is the folder in which the module resides. In order for python to treat it as a package. It must include a file named __init__py (module). If you import it as a normal module, the content of the file is the contents of the package. For example, there is a package named constants , the file constants/__init__.py includes the statement pi=3.14, So you can do this:

Import constants

Print constants. Pi

In order to place the module inside the package. Put the module directly in the Package folder.

Explore Modules

how to explore the modules independently is an invaluable skill. You may encounter a lot of useful modules in your career.

What's in the module

The most straightforward way to explore modules is to study them in the python interpreter.

The first thing to do is import it.

If there is a standard module called copy:

>>> Import Copy

Usedir

Viewing what is included in a module enables you to use the dir function, which lists all of the properties of the object (and all functions, classes, variables, and so on) of the module.

>>> dir(copy)

[' Error ', ' pystringmap ', ' _emptyclass ', ' __all__ ', ' __builtins__ ', ' __doc__ ', ' __file__ ', ' __name__ ', ' __package__ ', ' _ Copy_dispatch ', ' _copy_immutable ', ' _copy_inst ', ' _copy_with_constructor ', ' _copy_with_copy_method ', ' _deepcopy_ Atomic ', ' _deepcopy_dict ', ' _deepcopy_dispatch ', ' _deepcopy_inst ', ' _deepcopy_list ', ' _deepcopy_method ', ' _deepcopy_ ' Tuple ', ' _keep_alive ', ' _reconstruct ', ' _test ', ' Copy ', ' deepcopy ', ' dispatch_table ', ' Error ', ' name ', ' t ', ' weakref '

Some names begin with an underscore-implying that they are not intended for use outside the module. Filter to them:

>>> [n for N with dir (copy) if not N.startswith ('_')]

[' Error ', ' Pystringmap ', ' Copy ', ' deepcopy ', ' dispatch_table ', ' Error ', ' name ', ' t ', ' weakref ']

Allvariables

__all__ This name includes a list that is set inside the copy module.

>>> copy.__all__

[' Error ', ' Copy ', ' Deepcopy ']

It defines the public interface of the module.

To be more precise, it tells the interpreter: What does it mean to import all the names from the module?

Use the following code, for example, from copy import *. You can only use The functions in the __all__ variable. To import pystringmap , you have to explicitly implement it, or import copy and then use copy. Pystringmap, or use the from copy import Pystringmap.

This technique, like setting up __all__, is quite practical when writing a module.

Since there may be a whole bunch of variables, functions, and classes in the module that other programs do not need or want,__all__ will "politely" filter them out.

Assuming that no __all__is set, the import * statement defaults to the global name that all of the modules do not start with an underscore.

Use HelpGet help

For exploratory work. The interactive interpreter is a powerful tool. The mastery of the language determines the degree to which the module is explored. There's just one more standard function that can provide you with the information you need daily, and This function is called help.

>>> Help (Copy.copy)

Help on function copy in module copy:

Copy (x)

Shallow copy operation on arbitrary Python objects.

See the module ' s __doc__ string for more info.

>>>

In fact. The above help document is extracted from the document string of the copy function:

>>> Print copy.copy.__doc__

Shallow copy operation on arbitrary Python objects.

See the module ' s __doc__ string for more info.

>>>

Use help compared to directly checking document strings. The advantage is that you get a lot of other information.

Help (copy) will print out a lot of other information, here slightly;

Document

Not every module or function has a good document string (though it should be). In some cases, it may be necessary to describe very thoroughly how these modules and functions work.

The most practical document for learning Python programming is the python library Reference. It has a descriptive description of all the modules in the standard library.

Use the source code

For those who want to really understand the Python language. To understand the module, can not be separated from the source code.

Reading the source code is actually the best way to learn python--in addition to writing your own.

Real reading is not a problem, but the problem is the source. Suppose you want to read the source code for standard module copy. One option is to check the sys.path. Then find it yourself. Another is to check the __file__ property of the module :

>>> copy. __file__

' D:\\software (x86) \\Python27\\lib\\copy.pyc '

Note: Some modules do not include any python source code that can be read . They may have been incorporated into the interpreter (for example , the sys module), or they may have been written in the C language.

Basic Python Tutorial _ Learning Note 12: Charging time-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.