Day 21 module, the package import file directory specification

# Today's content

* Import module

`` Python `
" ""
1. What is the module
module is (os application file processing module, the application time module) aggregate function of a series of
modules have three sources
1. Built-in module
2. The third-party modules
3 custom modules
module four performance format
1. use the py file written in python
2 has been compiled as a shared library or DLL C or C ++ extensions
3. put together a series of modules organized into folders (folder there __init__.py a file folder called package)
4. written in C and is connected to the built-in module python interpreter

2. Why do you use the module
1. Use the built-in or third-party modules benefits are: ism, greatly enhance the development efficiency
2. Use a custom module benefits are: extraction procedures need to use more public places the function module defined as reduction of redundant code
(the program is a multi-file, multiple files will need to use all the functions in one place for everyone to find unity)

3. How to use modules
premise: we must distinguish who is the executable file, who is a module to be imported
"" "
` ``

#### import use

Python `` `
" ""
New execution file a two py is introduced
"" "
# md.py
Print ( 'from The md.py')
Money = 1000
DEF Read1 ():
Print ( 'MD', Money)
Read2 DEF ():
Print ( 'md module')
Read1 ()
DEF Change ():
Global Money
Money = 0

# run.py
Money = 66
Import # md file name is the name of the module and md.py md

# Right-run, execute the md file, multiple imports will not run more than once
. "" "
1. The first import of three things happens module
1. generates a name space module
2. Execute the file md.py, will perform name generated in the process are placed in the module namespace
'money': memory address 1000
'read1': memory address read1 function
'read2': memory address read2 function
'change': memory address change function
icon understand better effect
3. module name to get a space in the name of the current executable file, which points to the name of the name space module
that is:
Now run the md file, it will certainly create a namespace, all the md file names binding relationship with the value save up

run also run a file, it will certainly create a namespace, the money went to the store md
'money': memory address 66 of the
'md': name address md.py space of
2. after the import is a direct reference to the results of the first import will not re-execute the file
"" "
syntax # 1. perform file access module namespace name: the name of the module name
print (md.money) # named Road name of the file you want to name with md money, certainly not conflict with the name of the currently executing file
to the current namespace name of money to perform file money #

Print (md.read1)
Print (md.read2)
Print (md.change) # print to get the memory address of the function performed by the impulse >>> bracketed

# One call read1, read2, change clear repeatedly to find the name of the law
md.read1 () # md looking for a file in Money
md.read2 () # looking for money md file
md.change () # modified md file is money


Introducing a plurality of modules # line (not recommended)
Import OS, SYS, Time
since introduced to the module # Name Alias
import xxxyyy as xy

"" "
Import Import Module Summary:
must be prefixed when in use: the module name.
Advantages: by name to a name to a name space, certainly not conflict with the current namespace name
Cons: Whenever use the module will need to add the module name prefix
"" "
` ``

 

### from…import...

`` Python `
# still above two documents, for example
from md import Money
from md import Money
" ""
from ... import ... three things have taken place, before the two import like import, only the last a little bit different
1. generates a name space module
2. execute the file md.py, the name of the implementation process are generated into the name space module
3. direct to get a file name in the current implementation of the corresponding to the module name is the name of
'money': md file Money
"" "
# 1.
Money = 888
from md Import Money
# 2.
from md Import Money
Money = 888

# Summary
"" "
advantages: no need to use the prefix plus, more concise
Cons: may the name of the current conflict in the namespace
" ""
from md Import Read1
Money = 999
Read1 () # function call in the definition phase has been fixed dead, there is no relationship with the calling location here is only the implementation of the modified file namespace name! ! ! Illustrates appreciated
# another example evidence
Chang () # value is modified, the implementation of the money module file pointed to money nothing
Print (money)

# Learn
from md import * # * representatives to get all the names (not recommended) from imported modules, because the name is likely to conflict with the name of the current space
# * Import __all__ supplement is inside __all__ listed all the names
`` `

 

Import module ### cycles

Python `` `
" ""
Module
m1.py
Print ( 'being imported M1')
from M2 y # Import three things to occur in the first import
X = 'M1'
m2.py
Print ( 'being imported m2')
import the X-M1 from
the y-= 'M2'
run the file
run.py
import M1 # three things first import to happen
. "" "
# step by step analysis, performed first run, run to produce the corresponding namespace
# import m1, because it is first import will create a m1 corresponding namespace
code is # run m1 is found in m1 and guide the m2, m2 is the first import
# create m2 namespace, perform m2 code
# m2 in need to find in m1 x this time has not made out of x
"" "
the problem with this phenomenon is circulating imported, the guide m1 m2, m2 m1 in turn guide the
emergence of circulating means imported your program design is unreasonable, need to be redesigned
" " "

# Solve the problems caused by the import cycle
# 1 way: the statement cycle imported into the name behind the defined
print ( 'being imported M1')
the X-= 'M1'
from the y-M2 Import

print ( 'being introduced M2')
Y = 'M2'
from M1 X Import


# Embodiment 2: The loop statement introduced into the function
print ( 'being imported M1')
DEF F1 ():
from M2 Import Y
print ( 'm1.f1 >>> Y:', Y)
X = 'M1'

print ( 'being introduced M2')
DEF F2 ():
from M1 X Import
print ( 'm2.f2 >>> X:', X)
Y = 'M2'
# illustrated appreciated

# Summary: Before importing, ready to let its name
`` `

#### judgment py file is imported as a module or executable file

Python `
IF the __name__ == '__main__': # when a file is directly performed
if __name__ == 'py file name' # When a file is imported
`

Find the order of ### modules

`` Python `
" ""
query sequence module
1. start looking for may have been loaded in memory of the
2 built-in module
3.sys.path list inside a path to look at each
needs to know the list of the first path sys.path is the current file is the folder where the execution
ps: python module also supports importing directly from the zip archive in
"" "

# Validate the first point, looking to find a memory module start looking to see module is not already loaded
. "" "
Define a module, imported in another file, and then execute the file active sleep 10s, quick to speak during the module delete the file, find the code after execution of the file can still be accessed sleep
but once the program finishes running, the error will again perform the
Import Time
Import M1
the time.sleep (10)
Import M1
m1.f1 ()
"" "

# Note that py file name of your new best not to already existing module name conflicts time module, for example
`` `

#### a little bit more complicated cases

`` Python `
# To turn the module in a folder, execute files and folders with different levels at the same level module file
import md. # saved because of memory, built-in did not, sys.path is to execute the current file is located folder to find the file
# in order to solve, need to use sys.path.append () to the folder where the file module added to it

# Do not want to solve with the above, it can be used in the following ways
from ... import ...

from dir1.dir2 import md
```

 

Absolute import ### module

`` Python `
# again stressed: imported modules have to make clear the executable file and the import file, sys.path is based on the folder where the file is executed
- the absolute module import
-dir1
-m1.py
-m2.py
-run .py
files from dir1 import m1 # folder where the executable file run.py is "absolutely module import" to the folder can be found dir1 basis and thus can be found inside the m1

# One more example to confuse the people
- absolute import module
-dir1
-m1.py
-m2.py
-run.py
# m1 M2 directly guide


# And then study it again
- absolutely module import
-dir0
-dir1
-m1.py
-m2.py
-run.py
# module to import all the files are subject to perform file
# can use sys.path.appen be added to dir0 environment variable

"" "
Summary: begin to execute the file (based on sys.path) find the relationship between the layers, called the absolute import
advantages: executable file to be imported with the module can be used
Disadvantages: All imports are required to sys.path to play starting point, the import of trouble
. "" "
` ``

Introducing relative module ####

`` Python `
" ""
relative imports: reference file currently resides in the folder starting Find
The document represents the current location of the file folder
.. on behalf of a folder
... on behalf of an upper level folder

advantage: import more streamlined
disadvantages: can only be used in the module is imported, the file can not be executed with
"" "
# Note, however relative imports can only be used in the imported module folder, the file can not be executed used

 

 

 

 

 

 

 

 

Package #

Three sources speak when spoken module module of the four performance format

`` `python
module has three sources
1. Built-in module
2. The third-party modules
3. custom modules
four kinds of performance format module
1. Use python py written document
2. has been compiled as a shared library or DLL C or C ++ extensions
3. the series of modules grouped together in the folder (a __init__.py file folder, the folder called package)
4. written in C and is connected to the built-in module python interpreter


The origin of the presentation modules and packages #

"" "
What is a package
file containing the package is a __init__.py file folder
essentially modules can be imported, files are also included inside the package to be used to import
2. Why should pack
folders are used to better manage files, and package designers is to facilitate better organization module module
. "" "

# Build a folder containing a __init__.py (p1) was built in the same level of py file into the folder analysis process
. "" "
Memories of imported modules three things
1. Generate a module namespace
2. execution module code in the file name will be generated during execution are thrown into the namespace
3. get the name of the currently executing a file, the name is pointing to the name space module

Question: The second step is to import the module code execution documents, now is a folder, then the executive who does who threw it?

Import package deduced three things
1. __init__.py files in the package as a reference to generate a namespace
2. Run the code in __init__.py file package, the name is generated during execution are thrown namespace
3. get the name of a file in the current execution p1, p1 is the point __init__.py namespace
"" "
# python3 verify if a folder which does not contain __init__.py also not being given
# switching python2 found to direct error
# python2 that is inside the package must have __init__ file, python even if no error will not


# Verify the import package is the point __init__.py file
# access the module's name, in fact, go __init__.py file to find the name
`` `

#### Find name

`` Python `
# above derivation guide package is actually pointing __init__.py file to access the file name based on inside, so it might as well build a py file
# import the package is to be found inside the package all the py file name and not just __init__ file

"" "
Do not go around, talking too complicated to talk directly to two angles


The first angle: user package
user package after the download finished package, just make sure to find the path where the packet in his inside normal program and import it
namely the use of environment variables to manipulate sys.path
the package is located on a folder path to the environment variable (user needs to know is the download module or pack where is a folder, you just download a software, you definitely have to know where to go next)

Import statements. The left certainly must be a package

The second angle: package designers
to ensure that all modules are able to write their own top-level package __init__.py be found using the module relative to import
benefits are the highlights:
1. Module name change does not affect the internal lookup
2. No will be confused by the concept of nested layers of relationships and execute files into file
"" "
` ``

 

Guess you like

Origin www.cnblogs.com/AaronY/p/12596290.html