Python imports functions that reference other files (continuously updated)

Construct the initialization file structure, take this as an example.

Three-level file structure

Insert image description here

  • 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.

Insert image description here
Insert image description here
Insert image description here
Insert image description here

  • 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()

Insert image description here

  • 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()

Insert image description here

(2)直接引入函数

  • Introduce a single function
from d import functionD

def functionC():
    print("引入functionC")
functionD()

Insert image description here

(3)引入全部函数

from d import *

def functionC():
    print("引入functionC")
functionD()

Insert image description here

【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()

Insert image description here

(2)直接引入函数

  • Just write the function name directly when calling
from A.a import functionA

def functionC():
    print("引入functionC")

functionA()

Insert image description here

(3)引入全部函数

from A.a import *

def functionC():
    print("引入functionC")

functionA()

Insert image description here

【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

Insert image description here

(1)只引入a.py文件

  • Call a.functionA()
import sys
sys.path.append("../A")
import a
def functionB():
    print("引入functionB")
a.functionA()

Insert image description here

(2)直接引入函数

import sys
sys.path.append("../A")
from a import functionA 
def functionB():
    print("引入functionB")
functionA()

Insert image description here

(3)引入全部函数

import sys
sys.path.append("../A")
from a import *
def functionB():
    print("引入functionB")
functionA()

Insert image description here

Guess you like

Origin blog.csdn.net/weixin_45725923/article/details/131625424