From C # To Python -- 5 modules and packages

Source: Internet
Author: User

 

This chapter is the last part of the series of serialization from C # To python. It is simple to introduce how to use modules and packages in Python. If you are familiar with this part of the content, do not waste any time reading it. Write this chapter to complete the entire series, there is nothing new (This chapter mainly refers to Chapter 8 "modules and packages" in "Python essentials reference").

 

Module 5.1

All Python scripts are saved using text files with the extension py. One script can be run independently or imported to another. When a script is imported and run, it is called a module ). The module is organized by python.Code.

The module name is the same as the script file name. For example, if you have compiled a script named items. py, you can use the import items statement in another script to import it. During the import, the python interpreter first searches in the current directory of the script. If not, it searches in the path included in SYS. Path.

When importing a module, Python does the following:
(1) create a namespace for the objects defined in the module File. Through this namespace, you can access the functions and variables defined in the module;
(2) execute the module file in the newly created namespace;
(3) create an object named module file. This object references the module namespace, so that you can access functions and variables in the module through this object, such:

  1 ImportSys
2  PrintSYS. Path

To import multiple modules at the same time, use commas to separate them, for example, import sys, OS;

You can use the as keyword to change the referenced Object Name of the module, for example, import OS as system;

You can also use the from statement to directly import the objects in the module to the current namespace (reference objects of the module namespace are not created), such as: From socket import gethostname;

The from Statement supports comma-separated objects. You can also use an asterisk (*) to represent all objects starting with an underscore in the module, for example, from socket import *. This is an easy-to-use method, I often use it, but it is better to know whether it will overwrite the function name in the current namespace before using it. In short, it is not a good habit :)

In addition to Python scripts (not limited to py, but also PyC and Pyo), the import statement can also import C or C ++ extensions (compiled as a shared library or DLL file), package (including multiple modules for a while) and built-in modules (written in C and linked to the python interpreter ). Except for the package, I have never used the other two :(

When the python interpreter imports a py file for the first time, it will try to compile it into a bytecode file. The extension of this file is usually. pyC is the code that has completed the syntax check and translated into virtual machine commands. Later import operations will directly read The. PyC file instead of the. py file, which is generally faster.

 

5.2 packages

Python modules can be organized as packages by directory ). In general, we organize multiple closely related modules into a package to facilitate maintenance and use, while effectively avoiding namespace conflicts. To create a package, create a folder named "package name" and create a _ init __. you can store script files, compiled extensions, and sub-packages in this folder as needed.

A typical package may have the following structures:

  1   Package1  /  
2 _ Init __ . Py
3 Subpack1 /
4 _ Init __ . Py
5 Module_11.py
6 Module_12.py
7 Module_13.py
8 Subpack2 /
9 _ Init __ . Py
10 Module_21.py
11 Module_22.py
12 ......

If _ init _. py exists in the directory, it indicates that the directory should be processed as a package. In the simplest example, __init __. py is an empty file, but we usually need __. in py, initialize some packages or set some variables.

The most common variable is _ all __. When the package user imports data using the from pack import * Statement, the system searches for the variable _ all _ In the _ init _. py file in the directory pack. _ All _ is a list that contains the names of all modules to be imported, for example, __all _ = ["M1", "m2 ", "m3"] indicates that the three modules will be imported when the from pack import.

If _ all __is not defined, from pack import * does not guarantee that all sub-modules are imported. Therefore, you can either use _ init. py __or explicitly import the sub-module to ensure that it is imported, for example, import pack. M1, pack. m2, pack. m3.

 

5.3 Summary of this Chapter

This chapter describes how to use modules and packages in Python. The main points are as follows:

(1) The module is a Python script file that can be imported;
(2) A package is a bunch of modules and sub-packages organized by directory. The _ init _. py file in the directory stores the package information;
(3) You can use the import, import as, form import statements to import modules and packages.

In short, modules and packages are an effective way to physically organize Python code reuse, which is a bit similarProgramAssembly ). Python beginners do not have to build their own modules and packages, but must learn to use a variety of packages, which is what python is powerful in: Python with a variety of battery. When you want to complete a function, it is best to search for whether related packages can be reused (in most cases, because too many people are contributing to python in various fields ). In addition, the vast majority of Python packages are open-source, and studying excellent code is also an effective way to improve programming capabilities.

 

For more information, see:

The series from C # To Python has been fully written today. Thanks to your support, encouragement, and criticism, I can continue to improve and improve. After reading this serialization, we should be able to cope with the python syntax for a while. Of course, there are still many things that need to be learned in combination with the specific application fields. Here we recommend some useful books:

[1] scientific computing: This is the main position of my application of Python, we recommend hyry Studio "using python for scientific computing" (see http://pyscin.appspot.com/html/index.html ), I personally think that an excellent original book (I do not know why such a good book is not officially published. I admire the author's RP !).

[2] GUI development: If you use wxpython, you must see "wxpython in action" (Chinese Version see http://wiki.woodpecker.org.cn/moin/WxPythonInAction); and I personally mainly use pyqt4, in this regard, it is recommended to read the book is chainshu translation of pyqt4 programming Introduction "(see http://pyqt-doc-cn.googlecode.com/svn/trunk/Introduction_to_PyQT4/doc/r54/index.html ). If the English is good, we recommend reading rapid GUI programming with Python and QT (English PDF: http://householdcommandmodule.googlecode.com/files/Rapid.GUI.Programming.with.Python.and.Qt.Oct.2007.pdf ).

[3] web development: I haven't covered this yet. There are a lot of Django materials on the Internet, and other Python web development frameworks are also versatile. Find them by yourself :)

[4] mobile development: recently prepared to use pys60 to do something small, but has been unable to find time to download the "pys60 Library Reference" (Chinese Version address: http://www.woodpecker.org.cn: 9081/doc/Python/_ pdf/pythonfors60_4244_20.cn_doc.pdf). It has never been time to read it, so it is not recommended, but the official stuff should be poor. In addition, lucker's blog in the garden has some excellent information about pys60 development.ArticleAlthough I have added my favorites, I still have no time to read them in detail.

Final Statement: Although I did not write well, it also took me a lot of time and effort, so I hopeReprinted friends, please indicate the source!

 

End of serialization

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.