I. Modules in python
Friends who have experience in C programming all know that if you want to quote sqrt function in C language, you must introduce math.h header file with the statement # include < math.h>, otherwise you can't call it normally.
So in Python, what if you want to refer to some other functions?
In Python, there is a concept called module, which is similar to the header file in C language and the package in Java. For example, to call sqrt function in Python, you must introduce math into this module with import keyword. Here's a look at the module in Python.
Popular point: A module is like a toolkit. To use the tools in the toolkit (like functions), you need to import the module.
The concept of module:
- Each python source code file ending with the extension py is a module
- Module name is also an identifier, which should conform to the naming specification of identifier.
- Global variables, functions and classes defined in modules are tools for direct use by the outside world.
- Modules are like toolkits. To use the tools in this toolkit, you need to import the module first.
Two, import
Introducing a module in Python with the keyword import, such as referring to the module math, can be introduced with import math at the beginning of the file.
Import import
import module name 1, module name 2 # is not recommended
Note: When importing modules, each import should have a single line (recommendation)
import module 1 import module 2
After importing
Use the tools provided by the module through the module name -- global variables, functions, classes
Specify module aliases only with as
If the module's name is too long, you can use as to specify the module's alias for easy use in your code
import module name 1As module alias
Note: Module aliases should conform to Torpedo Naming Specification
Why add the module name?
Because there may be a case where functions with the same name are contained in multiple modules, the interpreter cannot know which function to call if it is called only by the name of the function. So if a module is introduced like this, the calling function must be named with the module name.
3. from ____________ import
Import from...
- If you want to import some tools from a module, you can use the way from...import.
- The import module name is a one-time import of all the tools in the module and accessed by the module name/alias
# Importing a tool from a module from module name import tool name # can specify aliases for tools through as
After importing
- You don't need to use the tools provided by the module in the way of the module name.
- Tools provided by modules can be used directly -- global variables, functions, classes
Be careful:
- If two modules have functions with the same name, the function imported after name overrides the function imported first.
- import code should be written uniformly at the top of the code when developing, making it easier to detect conflicts in time.
- For a certain immortal conflict, you can use the as keyword to give an individual name to one of the tools.
from...import *
# Import all tools from modules from module name import*
Be careful:
This kind of mage is not recommended, because the function rename does not have any hints, it is not easy to solve problems.
Case study:
Demo.py (custom module)
#global variable
title = "Module 1"
#function
def say_hello():
print("I am%s"%title)
#class
class Dog(object):
pass
#class
class Cat(object):
pass
Using demo.py module in test.py
#Import all tools in the module and specify an alias for the module myTest
import demo as myTest
#All tools in the import module are not recommended, and the tools with the same name are not easy to check.
#from...import *
#from...import Some tools in import module( Dog Class)
from demo import Dog
#For import tools Cat Class specifies an alias Test_Cat,Prevent tool renaming with other modules
from demo import Cat as Test_Cat
myTest.say_hello()
dog=Dog()
cat=Test_Cat()
4. Search Path of python Module Import
- Home directory of the program
- PTYHONPATH directory (if set)
- Standard connection Library Directory (generally in / usr / local / lib / Python 2.X/)
- The content of any. pth file (if it exists). New functionality allows users to add effective directories to the module search path to list directories line by line in text files with the. pth suffix.
- When these four components are combined, they become sys.path.
- When the python import module is used, it is searched under the directory list in sys.path.
- sys.path is the path set of python's search module and is a list.
- View the sys.path method:
import sys
print(sys.path)
['C:\\Users\\Se7eN_HOU\\Desktop\\Tools\\sublimetext3\\Sublime Text Build 3176 x86',
'C:\\Program Files\\Python37\\python37.zip',
'C:\\Program Files\\Python37\\DLLs',
'C:\\Program Files\\Python37\\lib',
'C:\\Program Files\\Python37',
'C:\\Users\\Se7eN_HOU\\AppData\\Roaming\\Python\\Python37\\site-packages',
'C:\\Program Files\\Python37\\lib\\site-packages']
Import Module Path at Program Execution
import sys
#because sys.path It's a list, so you can add a custom module path later
sys.path.append("/home/Se7eN_HOU")
#adopt insert You can insert the path ahead
sys.path.insert(0,"Home/Se7eN")
print(sys.path)
The results are as follows:
['Home/Se7eN',
'C:\\Users\\Se7eN_HOU\\Desktop\\Tools\\sublimetext3\\Sublime Text Build 3176 x86',
'C:\\Program Files\\Python37\\python37.zip', 'C:\\Program Files\\Python37\\DLLs',
'C:\\Program Files\\Python37\\lib', 'C:\\Program Files\\Python37',
'C:\\Users\\Se7eN_HOU\\AppData\\Roaming\\Python\\Python37\\site-packages',
'C:\\Program Files\\Python37\\lib\\site-packages',
'/home/Se7eN_HOU']
5. Module Making
1. Define your own modules
In Python, every Python file can be used as a module, and the name of the module is the name of the file.
For example, there is a file called test.py, which defines the function add in test.py.
def add(a,b):
return a+b
2. Call your own module
In the demo.py file, you can import the test first, then call it through test.add(a,b), and of course you can import it from test import add.
import test
result = test.add(1,2)
print(result)
The results are as follows:3
3. Test Module
In practice, when a developer has written a module, in order to make the module achieve the desired effect in the project, the developer will add some test information to the PY file by himself, such as: test.py file.
def add(a,b):
return a+b
#Used for testing
ret = add(11,22)
print("in test.py Test 11+22 = %d"%ret)
If this file is introduced into the demo.py file at this point, think about whether the code tested will also execute.
import test
result = test.add(1,2)
print(result)
The results are as follows:
in test.py test 11+22 = 33 3
At this point, it can be found that the test code in test.py should be executed only when the test.py file is executed separately, and should not be executed by reference in other files. To solve this problem, python has a variable _name when executing a file__
In the test.py file:
def add(a,b):
return a+b
#Used for testing
#ret = add(11,22)
#print("in test.py Test 11+22 = %d"%ret)
print("in test.py,__name__ is %s"%__name__)
The results are as follows:
in test.py,__name__ is __main__
Import the test.py module into the demo.py file and run as
import test
result = test.add(1,2)
print(result)
The results are as follows:
in test.py,__name__ is test
3
Based on the results of the _name_ variable, it can be determined whether the python script executed directly or introduced to execute, thus enabling selective execution of test code.
The code in the test.py module is changed to:
def add(a,b):
return a+b
if __name__ == "__main__":
ret = add(11,22)
print("in test.py Test 11+22 = %d"%ret)
The result of running in test.py is as follows:
in test.py test 11+22 = 33
Import the test.py module in demo.py
import test
result = test.add(1,2)
print(result)
The results are as follows:3
In this way, the code we are testing in the open will not appear in other modules.
6. all in Module__
1. No _all__
test.py module
class Test(object):
def test(self):
print("---Test Class test Method---")
def test1():
print("---test1 Method---")
def test2():
print("---test2 Method---")
Import the test.py module in demo.py
from test import *
a = Test()
a.test()
test1()
test2()
The results are as follows:
The test method in the Test class Tes1 method Tes2 method
2. There is _all in the module__
test.py module
__all__ = ["Test","test1"]
class Test(object):
def test(self):
print("---Test Class test Method---")
def test1():
print("---test1 Method---")
def test2():
print("---test2 Method---")
demo.py module
from test import *
a = Test()
a.test()
test1()
test2()
The results are as follows:
---Test Class test Method---Traceback (most recent call last):
---test1 Method---
File "C:\Users\Se7eN_HOU\Desktop\Tools\sublimetext3\Sublime Text Build 3176 x86\demo.py", line 5, in <module>
test2()
NameError: name 'test2' is not defined
If there is a _all_ variable in a file, it means that only the elements in this variable will be imported from xxx import *.