[Python] Getting Started tutorial (4): modules in Python

Source: Internet
Author: User
Tags first string list of attributes

I have learned how to define the future function in a program and reuse code. If you want to reuse many functions in other programs, you need to use the module.

The module is basically a file that contains all defined functions and variables. To reuse a module in other programs, the file name of the module must be. py.


The module can be input from other programs to take advantage of its functions. This is also the method for using the python standard library. First, learn how to use the standard library module.
Use SYS module

Example 1 use the SYS module

#!/usr/bin/python# Filename: using_sys.pyimport sysprint('The command line arguments are:')for i in sys.argv:    print(i)print('\n\nThe PYTHONPATH is', sys.path, '\n')

Output

We recommend that you run the py file in the command line to view the effect:



The following describes how the above Code works.

First, we use the Import Statement to input the SYS module. Basically, this statement tells Python that we want to use this module. The SYS module contains functions related to the python interpreter and its environment.


When Python executes the import sys statement, it searches for the SYS. py module in the directory listed in the SYS. PATH variable. If this file is found, the statements in the main block of this module will be run, and this module will be available to you. Note that the initialization process is only performed when we input the module for the first time. In addition, "sys" is short for "system.

The argv variable in the SYS module specifies -- SYS. argv by using the point number -- one advantage of this method is that this name does not conflict with any argv variable used in your program. In addition, it clearly shows that this name is part of the SYS module.

The sys. argv variable is a list of strings (the list will be detailed in the following sections ). In particular, SYS. argv contains a list of command line parameters, that is, the parameters passed to your program using the command line.

If you use ide to write and run these programs, find a command line parameter method for the specified program in the menu.

Here, when we execute Python using_sys.py We Are arguments, we use the python command to run the using_sys.py module. The following content is passed to the program as a parameter. Python stores it in the SYS. argv variable for us.

Remember, the script name is always the first parameter in the SYS. argv list. So here, 'using _ sys. PY 'is sys. argv [0] And 'We' are sys. argv [1] and 'are' are sys. argv [2] and 'arguments' are sys. argv [3]. Note that python starts counting from 0, not from 1.

SYS. path contains the list of directory names of the input module. We can see that the first string of SYS. Path is null -- this empty string indicates that the current directory is also part of SYS. path, which is the same as the environment variable of pythonpath. This means you can directly enter the module in the current directory. Otherwise, you must put your module in one of the directories listed in SYS. Path.

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. So now you know what the. PyC files actually are.

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. In general, you should avoid using the import statement instead of from .. import, because this will make your program easier to read and avoid name flushing.

Burst.

Module _ name __
Each module has a name. In the module, you can use statements to find the module name. This is particularly useful in one scenario-as mentioned above, when a module is input for the first time, the main module of this module will be run. What should we do if we only want to run the main block when the program itself is used, but do not run the main block when it is input by other modules? This can be done through the _ name _ attribute of the module.

Use the _ name _ of the module __
Example 2 use the _ name _ of the module __

#!/usr/bin/python# Filename: using_name.pyif __name__ == '__main__':    print('This program is being run by itself')else:    print('I am being imported from another module')

Output
$ Python using_name.py
This program is being run by itself

$ Python
>>> Import using_name
I am being imported from another module
>>>

Each Python module has its _ name __. if it is '_ main _', this indicates that this module is run independently by users and can be properly operated.


Create your own modules
Creating your own modules is very simple. Every Python program is also a module. Make sure it has the. py extension. The following example will make it clearer.

Create your own module
Example 3 how to create your own module

#!/usr/bin/python# Filename: mymodule_test.pydef sayhi():    print('Hi, this is mymodule speaking.')version = '0.1'# End of mymodule.py

The above is an example of a module, which 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 in one of the directories listed in SYS. Path.

#!/usr/bin/python# Filename: mymodule_demo.pyimport mymodule_testmymodule_test.sayhi()print('Version', mymodule_test.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
The following is a version using the from .. import syntax.

#!/usr/bin/python# Filename: mymodule_demo2.pyfrom mymodule import sayhi, version# Alternative:# from mymodule import *sayhi()print('Version', version)

The output of mymodule_demo2.py is exactly the same as that of mymodule_demo.py.

Dir () function
You can use the built-in dir function to list module-defined identifiers. Identifiers include functions, classes, and variables.

When you provide a module name for Dir (), it returns the name list defined by the module. If no parameter is provided, it returns the name list defined in the current module.

Use the Dir Function
Example 4 Use the Dir Function

$ python>>> import sys>>> dir(sys) # get list of attributes for sys module['__displayhook__', '__doc__', '__excepthook__', '__name__', '__stderr__','__stdin__', '__stdout__', '_getframe', 'api_version', 'argv','builtin_module_names', 'byteorder', 'call_tracing', 'callstats','copyright', 'displayhook', 'exc_clear', 'exc_info', 'exc_type','excepthook', 'exec_prefix', 'executable', 'exit', 'getcheckinterval','getdefaultencoding', 'getdlopenflags', 'getfilesystemencoding','getrecursionlimit', 'getrefcount', 'hexversion', 'maxint', 'maxunicode','meta_path','modules', 'path', 'path_hooks', 'path_importer_cache','platform', 'prefix', 'ps1', 'ps2', 'setcheckinterval', 'setdlopenflags','setprofile', 'setrecursionlimit', 'settrace', 'stderr', 'stdin', 'stdout','version', 'version_info', 'warnoptions']>>> dir() # get list of attributes for current module['__builtins__', '__doc__', '__name__', 'sys']>>>>>> a = 5 # create a new variable 'a'>>> dir()['__builtins__', '__doc__', '__name__', 'a', 'sys']>>>>>> del a # delete/remove a name>>>>>> dir()['__builtins__', '__doc__', '__name__', 'sys']>>> 

How it works
First, let's take a look at using dir on the input SYS module. We can see that it contains a huge list of attributes.

Next, we will use it instead of passing parameters to the Dir function -- by default, it returns the attribute list of the current module. Note that the input module is also part of the list.

To observe the role of Dir, we define a new variable A and assign it a value, and then test dir. We observe that the above values are added to the list. We use the del statement to delete the variables/attributes of the current module. This change is again reflected in the Dir output.

Note about Del-this statement is used to delete a variable/name after running. In this example, del A, you will no longer be able to use variable A -- it is as if it has never existed before.

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.