Python Learning (7)

Source: Internet
Author: User
Tags list of attributes
ArticleDirectory
    • 1. byte-compiled. PyC File
    • 2. From... import... statement
    • 3. The _ name _ attribute of the module
    • 4. Create your own modules
    • 5. dir () function
    • 6. Packages)
VII. module:

You can write functions to reuse them.CodeWe can also reuse a large number of functions through modules. There are multiple methods to write modules, but the simplest method is to create a file with the. py suffix to include the variables and functions that need to be reused. Another method is to compile the python interpreter's local language module. For example, a module written in C language can be compiled and used by Python code running on the standard Python interpreter. The module can beProgramImport to use its functions. This is why we can use the python standard library.
Let's take a look at how to use the standard library module:

 
# Filename: using_sys.py import sys print ('the command line arguments are: ') for I in SYS. argv: Print (I) print ('\ n \ nthe pythonpath is', sys. path, '\ n ')

Output:

C: \ Users \ Administrator> Python D: \ Python \ using_sys.py We Are arguments

The command line arguments are:

D: \ Python \ using_sys.py

We

Are

Arguments

The pythonpath is ['d: \ Python ', 'c: \ windows \ system32 \ python32.zip', 'c: \ PYT

Hon32 \ DLLs ', 'c: \ python32 \ Lib', 'c: \ python32 ', 'c: \ python32 \ Lib \ Site-pack

Ages ']

First, we use the Import Statement to import the SYS module. Essentially, this tells Python that we want to use this module. The SYS module contains functions related to the python interpreter and its working environment (that is, the system.

When Python executes the import sys statement, it looks for the SYS module. In this example, sys is one of the built-in modules, so Python knows where to find it. If the import is not a compilation module, that is, a module written in Python, the python interpreter searches for it in the directory listed in the SYS. PATH variable. If the module is found, the statements in this module will be executed and then you can use it (Note: Only top-level statements will be executed, that is, the statements in the main block ).

Note that a module is initialized only when it is imported for the first time.

In the SYS module, argv is referenced by a point number, that is, SYS. argv. It clearly states that this name is part of the SYS module. Another advantage of this syntax is that it will not conflict with the argv variable of the same name in your program. The variable SYS. argv is a string list (which will be explained in the subsequent chapter ). Specifically, SYS. argv is a list containing command line parameters, that is, the parameters passed to your program using the command line. If you are writing a program using IDE, find the method to specify command line parameters for the program in the menu.

Here, when we execute Python using_sys.py We Are arguments, we run the using_sys.py module with the python command, and the content after it is the parameter passed to the program. Python saves them to SYS. argv for our use.

Note: The Script Name to be run is always the first parameter of SYS. argv.

In this example, sys. argv [0] Is 'using _ sys. py', sys. argv [1] is 'we', sys. argv [2] is 'are', argv [3] Is 'arguments '. Note that the python subscript starts from 0 rather than 1. SYS. path contains a list of directory names indicating where to import the module.

1. byte-compiled. PyC File

Inputting a module is a relatively time-consuming task. Therefore, Python provides some tips to accelerate the input module. One way is to create byte-compiled files with the. PyC extension. Byte-compiled files are related to the intermediate state of the python converter. When you input this module from another program next time, The. PyC file is very useful-it will be much faster, because the processing required by some input modules has been completed. In addition, the files compiled by these bytes are not related to the platform.

Note:. PyC files are generally created in the same directory as their. py files. If Python does not have the write permission for this directory, the. PyC file will not be created.

2. From... import... statement

If you want to directly input the argv variable to your program (avoid using SYS. Every time you use it), you can use the from sys import argv statement. If you want to enter the names used by all sys modules, you can use the from sys import * Statement. This applies to all modules. Generally, you should avoid using the import statement instead of from .. import, because this will make your program easier to read and avoid name conflicts.

For example:

From math import * n = input ("Enter range:-") P = [2, 3] Count = 2a = 5 while (count <n ): B = 0for I in range (2, A): if (I <= SQRT (a): if (a % I = 0): # print, "is not a prime" B = 1 else: passif (B! = 1): # print a, "is a prime" P = P + [a] Count = count + 1A = a + 2 print P
3. The _ name _ attribute of the module

Each module has a name, and the module name can be obtained through some statements in the module. It is very convenient to find out whether the module runs independently or is imported. As mentioned above, when the module is imported for the first time, the code in the module will be executed. We can change the behavior mode when the module is executed independently. This can be done through the _ name _ attribute of the module.

For example:

Copy the file to the python directory before running the second Import Statement.

# Filename: using_name.py if _ name _ = '_ main _': Print ('this program is being run by itself ') else: print ('I am being imported from another module ')

Output:

C: \ Users \ Administrator> Python D: \ Python \ using_name.py

This program is being run by itself c: \ Users \ Administrator> Python

Python 3.2.2 (default, SEP 4 2011, 09:51:08) [MSC v.1500 32 bit (Intel)] on Win32

Type "help", "Copyright", "Credits" or "License" for more information.

>>> Import using_name

I am being imported from another module

Working principle:

Each Python module has its own _ name _ definition. If it is '_ main _', it implies that the module runs independently. We can perform some appropriate processing.

4. Create your own modules

Creating your own modules is simple, but you have been doing this all the time! Because every Python script is a module. Make sure it has the. py extension.

The following example will give you a clear understanding of it:

 
# Filename: mymodule. py def sayhi (): Print ('Hi, this is mymodule speaking. ') _ version _ = '0. 1' # End of mymodule. py

The above is a simple module. As you can see, this is nothing special than our usual Python program.

Remember that the module should be placed in the directory where the program to be imported is located, or in one of the directories listed in SYS. Path.

 
# Filename: mymodule_demo.py import mymodule. sayhi () print ('version', mymodule. _ version __)

Output:

C: \ Users \ Administrator> Python D: \ Python \ mymodule_demo.py

Hi, this is mymodule speaking.

Version 0.1:

Note that we also use the node number to access the module members. Python makes good use of the same symbol to bring a unique 'python' feeling, so that we don't have to learn more about syntax.

Below is a usageFrom .. ImportSyntax version:

 
# Filename: mymodule_demo2.py from mymodule import sayhi, _ version _ sayhi () print ('version', _ version __)

Mymodule_demo2.pyOutput andMymodule_demo.pyIdentical.

NOTE: If _ version __of the same name already exists in the module for importing mymodule, a name conflict will occur. In fact, this is very likely to happen, because every module uses _ version _ to declare its version, which is a common practice. Therefore, we recommend that you give priority to the import statement, although it may make your program longer.

You can also use: From mymodule import *, which will import all public names of the module, such as sayhi, but will not import _ version _ because it starts with a double underline.

5. dir () function

You can use the Dir function to list all identifiers defined by an object. For example, for a module, identifiers include functions, classes, and variables. When you provide a module name for the Dir () function, it returns all the names defined in it. If the Dir () parameter is null, all names defined in the current module are returned.

For example:

 

C: \ Users \ Administrator> pythonpython 3.2.2 (default, SEP 4 2011, 09:51:08) [MSC v.1500 32 bit (Intel)] on win32type "help", "Copyright ", "Credits" or "License" for more information. >>> dir (sys) ['_ displayhook _', '_ Doc _', '_ thook _', '_ name __', '_ package _', '_ stderr _', '_ stdin _', '_ stdout _', '_ clear_type_cache ', '_ compact_freelists', '_ current_frames', '_ getframe', 'api _ version', 'argv', 'builtin _ lele_names ', 'byteorder ', 'Call _ tracing', 'callstats', 'copyright', 'displayhook', 'dlhandle', 'dont _ write_bytecode', 'exc _ info', 'callback thook ', 'exec _ prefix', 'executable', 'exit ', 'flags', 'float _ info', 'getcheckinterval', 'getdefaultencoding ', 'getfilesystemencoding', 'getprofile ', 'getrecursionlimit ', 'getrefercount', 'getsize', 'gettrack', 'getwindowsversion', 'hversion', 'intern', 'maxsize', 'maxunicode ', 'meta _ path', 'modules', 'path', 'path _ hooks', 'path _ importer_cache ', 'platform', 'prefix', 'ps1 ', 'ps2 ', 'setcheckinterval', 'setprofile', 'setrecursionlimit ', 'settrack', 'stderr', 'stdin', 'stdout', 'subversion', 'version ', 'version _ info', 'waroptions', 'winver ']> Dir () # Get list of attributes for current module [' _ builtins __', '_ Doc _', '_ name _', '_ package __', 'sys '] >>> A = 5 # create a new variable 'A' >>> Dir () [' _ builtins __', '_ Doc _', '_ name _', '_ package _', 'A ', 'sys '] >>> del A # delete/remove a name >>> Dir () [' _ builtins _ ',' _ Doc __', '_ name _', '_ package _', 'sys ']

Working principle:

First, we can apply the Dir function through the imported SYS module. We can see that Sys contains a huge number of attributes.

Next, we will not provide parameters for the Dir function. By default, it returns the attribute list of the current module. Note that the imported module list is also part of the current module list.

To observe that dir determines the function, we define a new variable A, assign values to it, and then test the return value of Dir, we found that a value with the same name as variable A exists in the returned list. After we use the del statement to delete the variables/attributes of the current module, the changes are again reflected in the output of the Dir function.

Del annotation-this statement is used to delete a variable/name. In this example, after del A, you cannot access variable A-as it has never existed.

Note that the Dir () function can be used for any object. For example, execute Dir (print) to learn more about the attributes of the print function, or use Dir (STR) to list the attributes of the STR class.

6. Packages)

Now, you must begin to pay attention to organizing your program layers.

Variables are within the function, while functions and global variables are usually within the module. How to organize modules? This is the turn of the package debut. The package is only a folder that contains modules and carries a special file _ init _. py to indicate that the python folder is special because it contains the python module. Let's assume that you need to create a package named 'World', which contains sub-packages such as 'asia' and 'afica.

The following shows how to organize the folder structure:

-<Some folder present in the SYS. path>/-World/-_ init __. py-Asia/-_ init __. py-India/-_ init __. py-Foo. py-Africa/-_ init __. py-Madagascar/-_ init __. py-bar. PY

Packages are only used for hierarchical organizational modules. You will see many of its applications in the standard library.

Related Article

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.