日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > python >内容正文

python

python 各层级目录下的import方法

發布時間:2025/3/20 python 29 豆豆
生活随笔 收集整理的這篇文章主要介紹了 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_testdef 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

代碼:

''' 遇到問題沒人解答?小編創建了一個Python學習交流QQ群:579817333 尋找有志同道合的小伙伴,互幫互助,群里還有不錯的視頻學習教程和PDF電子書! ''' from test1 import * # the below is also ok #from test1 import dir_testfrom 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

代碼:

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

總結

以上是生活随笔為你收集整理的python 各层级目录下的import方法的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。