Python Basic---modules and packages

Source: Internet
Author: User
Tags define function


1. Module Import method


Common scenarios:

A module is a file containing python definitions and declarations, and the filename is the suffix of the module name plus the. Py , and the import module allows for the reuse of the function.


Import loaded modules are divided into four general categories:

1 code written using python (. py file)

2 c or C + + extensions that have been compiled as shared libraries or DLLs

3 Packages for a set of modules

4 built-in modules written and linked to the Python interpreter using C

A. Import statement

Python has many built-in modules, such as os,sys,time , etc., and can be custom modules, module packages,C extensions, etc., using the import Unable to differentiate imported module types

Import Module Name

Example: Import spam.py

Import spam(not including . PY)

To import multiple modules:

Import Os,time,sys

A module can contain definitions of executable statements and functions that are intended to initialize modules that execute only when the module name is first encountered when importing an import statement (an Import statement can be used anywhere in the program , and for the same module import many times , in order to prevent you to repeat the import,python optimization means: The first import after the module name is loaded into memory, the subsequent import Statement only adds a reference to a module object that has been loaded in large memory and does not re-execute the statements within the module

Each module is a separate namespace, defined in this module of the function, the namespace of the module as the global namespace, so that when we write our own module, we do not have to worry about our definition in our own module global variables will be imported, and the user's global variables conflict

What did the import module do:
1 Execute source file
2 global namespace with one source file
3 get a module name at the current location, point to the namespace created by 2

#测试一: Money does not conflict with Spam.money #test.pyimport spammoney=10print (Spam.money) output: from the spam.py1000 # Test two: Read1 and Spam.read1 do not conflict #test.pyimport spamdef read1 (): Print (' ======== ') spam.read1 () output: from the spam.pyspam-> read1->money1000# Test Three: global variable to perform spam.change () operation money is still #test.pyimport Spammoney=1spam.change () print (money) in spam Output: From the Spam.py1

Module alias function


Practice:

There are two clocks SQL module mysql and Oracle, depending on the user's input, choose different SQL functions

#mysql. Pydef sqlparse (): Print (' from MySQL sqlparse ') #oracle. Pydef sqlparse (): Print (' from Oracle Sqlparse ') #test. Pydb_type=input (' >>: ') if db_type = = ' mysql ': import mysql as dbelif db_type = = ' Oracle ': Import Oracle as DB Db.sqlparse ()

The way you alias an imported module is useful for writing extensible code, assuming there are two modules xmlreader.py and csvreader.pythat define function Read_data ( FileName): used to read some data from a file, but with a different input format. You can write code to selectively pick the Read module

if File_format = = ' xml ': import xmlreader asreaderelif File_format = = ' csv ': Import csvreader asreaderdata=reader.re Ad_date (filename)


B. From...import Statements

Method from module name import module name

Example:from Spamimport Money,read1,read2,change

If there are too many methods in the module, you can use:

From spam import * (deprecated, easy to conflict with file namespace)

__all__=[' money ', ' X '] # useful for from spam import * , then import money,x method
_money=1000 # useful for from spam import * , this method will not be imported

contrast import spam ' spam ' take it to the current namespace, must be spam. The name of the way, and from statement equivalent to import

#spam. Pyprint (' from the spam.py ') Money=0def read1 (): Print (' Spam->read1->money ', Money) def read2 (): Print (' Spam ->read2 calling read ') read1 () def Change (): Global Money money=0 # Execute file from spam import Money,read1,read2,cha Ngemoney=0print (Money) print (READ1) output: from the spam.py #首先执行spam. Py0 #仍然是当前执行文件的命名空 Money<function Read1 at 0x00000000026de950> in the room

Advantage: Use the name in the source file without prefix, easy to use

Cons: Easy to confuse with names in the current file's namespace

C. Module Search Path

The module executes only on the first import, and subsequent imports are the result of directly referencing the memory already present
Import Sys
Print (' spam ' in Sys.modules) # stores the modules that have been loaded into the

Note: The custom module name must not be the same as the module name that Python comes with

The order in which the modules are found is: modules that are loaded in memory, built- in modules->sys.path paths

Import timeimport importlibimport spam #导入模块会把硬盘中的模块内容加载到内存中time. Sleep () import spam #再次导入会直接从内存中查找, suddenly The module content print (Spam.money) importlib.reload (spam) #会重新加载模块 in the hard drive (used only in the test environment) print (Spam.money)


Import Sys

the search path for the print (sys.path) # module

The Sys.path is initialized from the following location

1 The current directory where the execution file resides

2 Ptyhonpath(contains a list of directory names, as with the shell variable PATH syntax)

3 dependent on the default specified during installation

To add a module path:

Import Sysprint (Sys.path) Sys.path.insert (0,r ' module path to add ') #插入模块路径sys. Path.append (r ' module path to add ') #追加模块路径


D. two uses for distinguishing python files

files Run as scripts (execute files) __name__ equals __main__
file as module is loaded runtime __name__ equals module name

# M1.pyimport Os,sysx=1def func1 (): Print (' from M1 ') def func2 (): Print ("from M2") def func3 (): Print (' from M3 ') # p    Rint (__name__) #文件当做脚本运行时__name__等于__main__ # file as module is loaded runtime __name__ equals module name if __name__ = = ' __main__ ': #当做脚本使用时才执行 func1 () Func2 () func3 () # run.py Import M1 #导入m1模块m1. FUNC3 ()

E. Package

Creating a folder in Python3 automatically creates a __init__.py

creating packages in Python2 requires manual creation of __init__.py

1. Whether it is an import or from...import form, it is the first time to be alert when you encounter a dot in an imported statement (rather than in use): This is the import syntax for packages

2. packages are directory-level (folder-level), folders are used to form a py file (the essence of the package is a directory containing __init__.py files)

3. Import the file, the resulting namespace name from the file,import package, the name of the resulting namespace is also derived from the file, that is, the __init__.py under the package , theimport package is the essence of the import of the file

Emphasize:

1. in Python3 , even if there is no __init__.py fileunder the package, import package will still not error, and in Python2 , the package must have the file, otherwise Import Packet error

2. The purpose of creating the package is not to run, but to be imported to use, remember that the package is just a form of the module, the package is a module

3. in the case of imports, the left side of the point must be a package


This article is from the "Lyndon" blog, make sure to keep this source http://lyndon.blog.51cto.com/11474010/1953171

Python Basic---modules and packages

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.