Module of python/module and package

Source: Internet
Author: User
Tags define function print print

python/module and Package Module 1. What is a module?

Module is the py file

2. Why use modules?

If you encode on the interpreter, the file that was written before the interpreter is closed does not exist, and can be permanently saved to disk if the module is used.

3. How do I use the module?

3.1 Import imports the module to use via Import
1#spam.py2Print('From the spam.py') 3 4 money=1000 5 6defread1 ():7Print('Spam->read1->money', 1000) 8 9defread2 ():10Print('Spam->read2 Calling Read')11Read1 ()12 13defChange ():14Global MoneyMoney=0

The 3.1.1 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 (the import statement can be used anywhere in the program and is imported multiple times for the same module. To prevent you from repeating the import, Python is optimized by loading the module name into memory after the first import and the second and third import will not work.

Import spam Import spam Import spam

We can find the module that is currently loaded from Sys.module, Sys.module is a dictionary that contains the mapping of the module name to the module object, which determines whether the import module needs to be re-imported.

Instance file:

Print ('from thespam') xx=11def  N ():    print("        ") def N1 (): Print ('   Took')    def Change ():    global  xx    XX=0

  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 own module in the definition of global variables will be imported, and the user's global variables conflict

< Span style= "color: #cc9900; Font-weight:bold ">   &NBSP;             
Conflict Test One
Import spamxx=112print(spam.xx) execution results from the spamProcess Finished with exit code 0
Conflict Test II
Import spamdef N (): print('------ ' ) SPAM.N () execution result from the Spamlook Process finished with exit code 0
Conflict Test Three
Import spamxx=111spam.change ()print(xx) execution results from the spam 111Process finished with exit code 0

Summary: Three things to do when importing a module for the first time:

1. Create a new namespace for the source file (spam module), and the functions and methods defined in spam are the namespaces that are accessed when Globa is used

2. Execute the wrapped code in the module in the newly created namespace, see initial import spam

3. Create a name spam to reference this namespace

Alias the module to make it easy to invoke:

Aliases are only useful in the current module

Improt and from ... Improt support the as module alias

Import spam as SM

Print (Sm.money)

The way you alias an imported module is useful for writing extensible code, assuming there are two modules xmlreader.py and csvreader.py that define function read_data (filename): Used to read some data from a file, However, different input formats are used. You can write code to selectively select read modules, such as

if file_fromat=='xml':    import  xmreader as Reader  elif fil _fromat=='csv':    Import  Csvreader as Readerdata=reader.read_date (filename)
3.2 from .... Import ...

Comparing the import spam, the namespace ' spam ' of the source file is brought into the current namespace, and must be spam when used. The way of the name

The FROM statement is equivalent to import, and a new namespace is created, but the name in the spam is imported directly into the current namespace, and the name is used directly in the current namespace.

Import N,n1

This allows the N,N1 function to be used directly at the current location, while still executing with the spam global namespace

Test A
fromimport nxx=222N () execution result from 11
Test Two
from import N1def N (): print('good ' ) N1 () execution result from 11

If there is a duplicate name read1 or read2, then there will be an overlay effect.

One particular point to note is that variable assignment in Python is not a storage operation, but a binding relationship, as follows:

 from Import xx,nxx=123   #  binds the name xx of the current position to the 123print (xx)     # Print the current name N (   # read spam.py in name xx still executes results  from the spam123  oneProcess finished with exit code 0

From spam Improt * Import all names from spam to the current location, in most cases our Python program should not use this type of import, because * is imported all, it is possible to overwrite the name you previously defined, and the readability is extremely poor, No problem importing in an interactive environment

 from Import # Import all the names in the module spam into the current namespace Print   print print print6 "' 8    Execution Result: 9 from the spam.py10 1111 <function n @ 0x1012e8158>12 <function N1 at 0x1012e81e0>13 <function Chan GE at 0x1012e8268>

can use __all__ to control * (for the new version)

Add a line to the spam.py

__all__=[' money ','read1# So in another file with the From spam import * This can import the two names specified   in the list 

For performance reasons, each module is imported only once, put into the dictionary sys.module, if you change the contents of the module, you must restart the program, Python does not support reloading or uninstalling the previously imported modules,

Some students may think of removing a module directly from the Sys.module can not be uninstalled, note that you deleted the Sys.module module object may still be referenced by other program components, so it will not be clear.

In particular, we refer to a class in this module, which produces many objects with this class, so that these objects have references to this module.

If it's just a module that you want to test interactively, use importlib.reload (), e.g. import importlib; Importlib.reload (ModuleName), which can only be used for test environments

def func1 ():     Print ('func1')

Import Time,importlib Import AA3 4 time.sleep ()#  importlib.reload (aa)6 aa.func1 ()

In 20 seconds of waiting time, modify the contents of func1 in aa.py, waiting for the result of test.py.

Open importlib comments, re-test

3.3 module as script execution

We can view the module name through the global variable __name__ of the module:
Run as script:
__name__ equals ' __main__ '

Import as module:
__name__=

Function: Used to control the. py file to perform different logic in different scenarios
if __name__ = = ' __main__ ':

defFIB (n):#Write Fibonacci series up to nA, b = 0, 1 whileb <N:Print(b, end=' ') A, b= B, A +bPrint()defFIB2 (n):#return Fibonacci series up to nresult =[] A, B= 0, 1 whileb <N:result.append (b) A, B= B, A +breturnresultif __name__=="__main__":    Importsys fib (int (sys.argv[1]))
3.4 Module Search Path

The Python interpreter automatically loads some modules at startup, and you can use Sys.modules to view

The module lookup order is to find the memory---------> not find the built-in---------> and then find the path--------> will error if not found.

3.5 Standard Modules

Python provides a library of standard modules that are built into the interpreter, which provides access to operations that are not part of the core of the language, but they are built-in, whether for efficiency or to provide access to the operating system primitives. These collection of modules are configuration items that rely on the underlying platform, such as the WinReg module only for Windows systems. It is particularly important to note that the SYS module is built into every Python interpreter

Sys.ps1
Sys.ps2
These two are valid only on the command line, and the result is that the interpreter is identified in interactive mode.


The variable sys.path is a list of strings that determines the path of the module search, initializes the default path from the environment variable Pythonoath, and initializes the value from the built-in if Pythonpath is not set, and we can modify it
Sys.path.append

ImportOsos.path.normpath (PATH)#Normalize paths, convert case and slash of patha= "/users/jieli/test1/\ \\a1/\\\\aa.py/. /..  "print (Os.path.normpath (a))  "'  print result: \users\jieli\test1  "" # application import Os,syspossible_topdir = Os.path.normpath (Os.path.join (Os.path.abspath (__file__ ), Os.pardir, # upper level  Os.pardir, Os.pardir)) Sys.path.insert (0,possible_topdir)     

3.6 dir () function

The built-in function dir is used to find the name defined in the module, returning an ordered list of strings
Import spam
Dir (spam)

If there are no parameters, dir () lists the name of the current definition


Dir () does not enumerate the names of the built-in functions or variables, they are defined in the standard module builtin, and can be enumerated,
Import Builtins
Dir (builtins)

Module of python/module and package

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.