1. 程式人生 > 程式設計 >python各層級目錄下import方法程式碼例項

python各層級目錄下import方法程式碼例項

這篇文章主要介紹了python各層級目錄下import方法程式碼例項,文中通過示例程式碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下

以前經常使用python2.現在很多東西都切換到了python3,發現很多東西還是存在一些差異化的。跨目錄import是常用的一種方法,並且有不同的表現形式,新手很容易搞混。有必要這裡做個總結,給大家科普一下:

1 同級目錄下的呼叫:

同級目錄下的呼叫比較簡單,一般使用場景是不同類的相互呼叫。不用考慮路徑問題,常用的格式是:from file import * 或者 from file import class/function 等。

下面以一個例子作為說明:

程式結構:

➜ dir_test git:(master) ✗ tree
.
├── pycache
│  └── test1.cpython-37.pyc
├── dir1
│  └── test3.py
├── test1.py
└── test2.py

程式碼:

from test1 import *
# the below is also ok
#from test1 import dir_test

def test_file2():
  print("this is test file2")

dir_test()
test_file2()

2 子目錄下的呼叫:

子目錄下的函式呼叫,正常的情況下,需要包含子目錄的,常用的格式如下:form dir1.file import * 或者: from dir1 import file等。

下面以一個例子說明:

➜ dir_test git:(master) ✗ tree
.
├── pycache
│  └── test1.cpython-37.pyc
├── dir1
│  ├── pycache
│  │  └── test3.cpython-37.pyc
│  └── test3.py
├── test1.py
└── test2.py

程式碼:

from test1 import *
# the below is also ok
#from test1 import dir_test

from dir1.test3 import *

def test_file2():
  print("this is test file2")

dir_test()
dir1_test()

3 上級目錄下的呼叫:

上級目錄呼叫要比上兩種複雜,這裡要用到sys函式,首先要在將要呼叫的檔案下面建一個空檔案:init.py 然後在呼叫這個檔案的檔案裡面新增:sys.path.append("…"),才可以呼叫成功:

下面是一個例子:檔案結構:

➜ dir_test git:(master) ✗ tree
.
├── pycache
│  └── test1.cpython-37.pyc
├── dir1
│  ├── init.py
│  ├── pycache
│  │  ├── init.cpython-37.pyc
│  │  └── test3.cpython-37.pyc
│  └── test3.py
├── dir2
│  └── test4.py
├── test1.py
└── test2.py

程式碼:

#!python3

import sys
sys.path.append("..")
from dir1.test3 import *
#import dir1

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支援我們。