Article directory
- Construct the initialization file structure, take this as an example.
-
- 【1】Function to import other files in the same directory and at the same level (`Function to import d.py file from c.py file`)
- 【2】Import files in other folders in the same directory but at different levels (`c.py function to import a.py files in folder A`)
- 【3】Import files in different directories (`b.py in file B imports functions in a.py file in file A`)
Construct the initialization file structure, take this as an example.
Three-level file structure
- Among them, folders A and B are at the same level as files c and d.
- Files a and b are at the same level.
- In order to facilitate testing, the contents of the initialization files a, b, c, d are as follows.
- In-file functions are used for test output.
- Different situations are explained below
【1】Function to import other files in the same directory and at the same level (
c.py文件导入d.py文件的函数
)
(1)只引入d.py文件
import d
def functionC():
print("引入functionC")
d.functionD()
- d.functionD() is required when calling functions in d
- You can also rename the imported file d
- Just add an as
import d as newNameD
def functionC():
print("引入functionC")
newNameD.functionD()
(2)直接引入函数
- Introduce a single function
from d import functionD
def functionC():
print("引入functionC")
functionD()
(3)引入全部函数
from d import *
def functionC():
print("引入functionC")
functionD()
【2】Import files in other folders in the same directory but at different levels (
c.py导入A文件夹内的a.py文件的函数
)
(1)只引入a.py文件
- Calling a function requires a file name. Function name such as a.functionA()
from A import a
def functionC():
print("引入functionC")
a.functionA()
(2)直接引入函数
- Just write the function name directly when calling
from A.a import functionA
def functionC():
print("引入functionC")
functionA()
(3)引入全部函数
from A.a import *
def functionC():
print("引入functionC")
functionA()
【3】Import files in different directories (
B文件中b.py导入A文件中a.py文件内的函数
)
前置条件:
- 【1】Introduce import sys and use sys.path.append(“…/”) to splice the path
- 【2】Set the folder to be imported as Sources Root
- This example sets the A folder as Sources Root
- New -> Mark Directory as -> Sources Root
(1)只引入a.py文件
- Call a.functionA()
import sys
sys.path.append("../A")
import a
def functionB():
print("引入functionB")
a.functionA()
(2)直接引入函数
import sys
sys.path.append("../A")
from a import functionA
def functionB():
print("引入functionB")
functionA()
(3)引入全部函数
import sys
sys.path.append("../A")
from a import *
def functionB():
print("引入functionB")
functionA()