溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

python各層級(jí)目錄下import方法代碼實(shí)例

發(fā)布時(shí)間:2020-09-15 19:23:41 來源:腳本之家 閱讀:159 作者:虛生 欄目:開發(fā)技術(shù)

這篇文章主要介紹了python各層級(jí)目錄下import方法代碼實(shí)例,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下

以前經(jīng)常使用python2.現(xiàn)在很多東西都切換到了python3,發(fā)現(xiàn)很多東西還是存在一些差異化的。跨目錄import是常用的一種方法,并且有不同的表現(xiàn)形式,新手很容易搞混。有必要這里做個(gè)總結(jié),給大家科普一下:

1 同級(jí)目錄下的調(diào)用:

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

下面以一個(gè)例子作為說明:

程序結(jié)構(gòu):

➜ 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 子目錄下的調(diào)用:

子目錄下的函數(shù)調(diào)用,正常的情況下,需要包含子目錄的,常用的格式如下:form dir1.file import * 或者: from dir1 import file等。

下面以一個(gè)例子說明:

➜ 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 上級(jí)目錄下的調(diào)用:

上級(jí)目錄調(diào)用要比上兩種復(fù)雜,這里要用到sys函數(shù),首先要在將要調(diào)用的文件下面建一個(gè)空文件:init.py 然后在調(diào)用這個(gè)文件的文件里面添加:sys.path.append("…"),才可以調(diào)用成功:

下面是一個(gè)例子:文件結(jié)構(gòu):

➜ 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

以上就是本文的全部內(nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持億速云。

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請(qǐng)聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI