Module management is one of the key knowledge in Python development, this article and you share is this part of the content, take a look at it, hope to learn Python help.
Import a new module
Create a calculate.py file
Print (' OK ')
def Add (x,y):
return x + y
def Sub (x,y):
return x-y
Then create a bin.py file to invoke the calculate.py module
Import sys
Import Calculate # Imports Calculate module, module will search in Sys.path
Print (Calculate.add (1,2)) # calls the Add method in the Calculate module, which needs to be written as Calculate.add ()
Print (Sys.path) # view Pyton Search Module
Run Result:
Ok3
[' D:\\\\python_script\\\\alex_test\\\\day20 ', ' d:\\\\python_script\\\\alex_test ', ' d:\\\\python35\\\\ Python35.zip ', ' d:\\\\python35\\\\dlls ', ' d:\\\\python35\\\\lib ', ' d:\\\\python35 ', ' d:\\\\python35\\\\lib\\\\ Site-packages ']
Using the From ... import method to invoke the method in the Calculate module
from calculate import add, Sub
Print (add(1,2)) # is invoked directly using Add ()
Run Result:
Ok3
Create alias
From calculate import add as plus # here the program can only call Plus, and add will fail
# Print(add (1,2)) Nameerror:name ' Add ' is not defined error
Print (Plus (1,2))
Run Result:
Ok3
calling modules in other directories
logger.py File Contents
def Write_log ():
Print ("Logging")
Called in two ways
#方法一: from Web.logger import Write_log
Write_log ()
Run Result:
Logging
#方法二: from web import Logger
Logger.write_log ()
Run Result:
Logging
Note that if the file contents of __ init__. PY are below the module, import and From...import will execute the statements in __ init__. py.
Note the path of the module when importing the module
Import Os,sys
Babe_dir = Os.path.dirname (Os.path.dirname (__file__))
# get the path and name of the current execution file via __file__
# Get the path to the previous level via Os.path.dirname ()
Sys.path.append (babe_dir) # System execution Environment add required path
Print (Sys.path)
Source: Network