table of Contents
Recap last lesson
https://www.cnblogs.com/foreversun92/p/11359938.html
A module of four forms
First, what is a module?
It is a series of functional module assembly, and a function is a function of the aggregate, and therefore the module can be seen as a function of a pile of aggregate. Py inside a file you can put a bunch of functions, so a py file can be seen as a module. If this file is named py module.py
, the module name is module
.
Second, the module of four forms
In Python, a total of four forms of modules:
- Custom modules: If you write a py file, write a bunch of functions in the file, it is called a custom module, namely using .py files written in python
- Third-party modules: has been compiled as a shared library or DLL C or C ++ extensions
- Built-in modules: written in C and link to the python interpreter built-in module
- Package: The module organized into a series of file folders together (Note: there is a __init__.py file folder under the file folder called package)
Third, why use a module?
- With a third party or the built-in module is an ism, it can greatly enhance the development efficiency.
- Custom module, the procedures used in our own public function, write a python file, then the component parts of the program can reference the ability to customize the module by way of import.
Fourth, how to use the module
Generally, we use the import and from ... import ... import modules.
Two, import and from ... import
Import, and is generally used import ... Import from ... module.
In the following code within the file spam.py Example.
# spam.py
print('from the spam.py')
money = 1000
def read1():
print('spam模块:', money)
def read2():
print('spam模块')
read1()
def change():
global money
money = 0
A, import the module name
# run.py
import spam # from the spam.py
import spam
import import module for the first time three things happened:
- Create a module to module, whichever namespace
- Execution module corresponding file, will perform the namespace name generated in the process are thrown into the module
- Get a module name in the current executable file
Repeat the import module will directly create good results before drinking it, the file will not repeat the module, that is repeated import will happen: spam = spam = memory address space module name
# run.py
import spam as sm
money = 111111
sm.money
sm.read1() # 'spam模块:1000'
sm.read2
sm.change()
print(money) # 1000
Introducing a plurality of modules
import spam, time, os
# 推荐使用下述方式
import spam
import time
import os
Two, from the module name import specific functions
# run.py
from spam import money
money = 10
print(money) # 10
from ... import ... first import module happened three things:
- Create a module to module, whichever namespace
- Execution module corresponding file, will perform the namespace name generated in the process are thrown into the module
- Get a name in the current namespace executable file, the name of the module directly to a particular name, which means you can not add any prefix directly
- Pros: do not add a prefix code more streamlined
- Disadvantages: easily conflict with the currently executing file namespace name
Import all functions within the file:
# spam.py
__all__ = ['money', 'read1'] # 只允许导入'money'和'read1'
# run.py
from spam import * # 导入spam.py内的所有功能,但会受限制于__all__
Three, import and similarities and differences from ... import ...
Same point:
- Both modules will execute the corresponding file, the two modules will have a namespace
- When both calling function to find the scope of the relationship, and calls need to go to define the position has nothing to do
difference:
- import need to add the prefix; from ... import ... no need to add the prefix
Third, the circulation import questions
First, what is circulating import?
# m1.py
print('from m1.py')
from m2 import x
y = 'm1'
- Creating m2 namespace
- Execution m2.py, the name of the generated execution thrown m2.py
- Get m2.x execution in the current document
# m2.py
print('from m2.py')
from m1 import y
x = 'm2'
- Creating m1 namespace
- Execution m1.py, the name of the generated execution thrown m1.py
- Get m1.y execution in the current document
# run.py
import m1
- Creating m1 namespace
- Execution m1.py, the name of the generated execution thrown m1.py
- M1 get the currently executing file
- If you run run.py, it will error
ImportError: cannot import name 'y'
- If you run m1.py, it will error
ImportError: cannot import name 'x'
- If you run m2.py, it will error
ImportError: cannot import name 'y'
Second, the solution
We can use the function syntax definition phase only identifying characteristics of problem-solving cycle of import, we can also solve the problem of circulation imported from the essence, but the best solution is not to appear import cycle.
2.1 Option One
# m1.py
print('from m1.py')
def func1():
from m2 import x
print(x)
y = 'm1'
# m2.py
print('from m2.py')
def func1():
from m1 import y
print(y)
x = 'm2'
2.2 Option II
# m1.py
print('from m1.py')
y = 'm1'
from m2 import x
# m2.py
print('from m2.py')
x = 'm2'
from m1 import y
Third, the module search path
A sequence module search path
Module is actually a file, if you want to execute the file, first of all need to find the path to the module (a folder). If the module file path and execute files are not under the same file directory, we need to specify the module's path.
The module search path refers to when importing module needs to retrieve folder.
When import modules lookup module sequence is:
- Start with the memory module has been imported looking
- Built-in module
- Environment variable sys.path looking in
import sys
print(f"sys.path: {sys.path}")
'''
['/Users/mac/Desktop/video/python/day16',
'/Users/mac/Desktop/video/python',
'/Applications/anaconda3/lib/python36.zip',
'/Applications/anaconda3/lib/python3.6',
'/Applications/anaconda3/lib/python3.6/lib-dynload',
'/Applications/anaconda3/lib/python3.6/site-packages',
'/Applications/PyCharm.app/Contents/helpers/pycharm_matplotlib_backend']
'''
He emphasized: The first value of sys.path is currently executing the file where the folder
1.1 start looking for validation memory
If, when we run run.py files, quickly delete mmm.py file, we will find the file will continue to operate without error, because the memory of them has been imported mmm. It will complain if we again run run.py, because mmm.py has been deleted.
# mmm.py
def f1():
print('from mmm.py f1')
# run.py
import time
import mmm
time.sleep(10)
import mmm
mmm.f1() # from mmm.py f1
1.2 built-in validation start looking
# time.py
print('from time.py')
# run.py
import time
print(time) # <module 'time' (built-in)>
1.3 verify the find from sys.path
If mmm.py in /Users/mac/Desktop/video/python
the next path, and the path to the executable file /Users/mac/Desktop/video/python/day16
, if ordinary import will be error, we can /Users/mac/Desktop/video/python
add to the environment variable sys.path protected from error.
# run.py
import sys
sys.path.append(r'/Users/mac/Desktop/video/python')
print(sys.path)
import mmm
mmm.f1()
Second, the search path to execute the document shall prevail
Assuming that the file, the code within the file directory structure we have described above are:
# m1.py
import sys
print('模块m1中查看的结果',sys.path)
# import m2
from dir1 import m2
m2.f2()
# m2.py
import sys
print(sys.path)
def f2():
print('from f2')
# run.py
import sys
print('执行文件查看的结果:',sys.path)
from dir1 import m1
Where the execution path run.py file is /Users/mac/Desktop/video/python/day16/模块搜索路径练习
, if we use directly in m1.py the import m2
import m2 will get an error while using from dir1 import m2
imported m2 will be successful, because the search path to the executable file prevail, dir1 and run.py is the same directory , so run.py environment variables can be found dir1; and m2 and run.py not the same directory, so run.py environment variable can not be found directly m2.
Fourth, the two uses Python file
A two uses, Python file
There are two uses python file a file is performed; the other is being introduced as a module.
Writing good a python file may have two purposes:
- Script, a file is the entire program, to be executed
- Module, stored in a pile of document function is introduced for use
# aaa.py
x = 1
def f1():
print('from f1')
def f2():
print('from f2')
f1()
f2()
# run.py
import aaa
If you run directly run.py will run directly aaa.py in f1()
and f2()
, but if we add in aaa.py in if __name__ == '__main__':
this sentence, you can prevent run run.py execution f1()
and f2()
. Because when aaa.py executed directly, i.e., as the execution file time __name__ == '__main__'
; when the module is used as running directly aaa.py __name__ == 'aaa'
. It can make aaa.py have different usage under different scenarios.
# aaa.py
x = 1
def f1():
print('from f1')
def f2():
print('from f2')
if __name__ == '__main__':
f1()
f2()
Summarize today
no