python下級模塊導入上級模塊出錯

首先看看我的文件結構:
在這裏插入圖片描述

我現在所在的文件是運算符重載.py模塊,需要導入test.py模塊和classfile文件夾裏的嵌套.py模塊,按照大部分人的習慣:
在這裏插入圖片描述

也沒有提示有錯誤,運行看看:
在這裏插入圖片描述

出錯了,查看了一些博客,有的解決方法是說運行文件只能爲最上級的,出錯時候得將運行模塊弄到最上層去,具體見博客:
https://www.cnblogs.com/ArsenalfanInECNU/p/5346751.html
現在我想要解決的是:低層級的模塊調用高層級的模塊,找到了兩種解決方式,第一種:

import os
import sys
path = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.insert(0, path)
import test
from classfile.嵌套 import Point

test.py內的內容是:

print("successfully import!")

來看看運行結果:
在這裏插入圖片描述

導入test.py模塊和嵌套.py模塊成功了。
看看第二種方法:

import os
import sys
sys.path.append(os.pardir)
# path = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# sys.path.insert(0, path)
import test
from classfile.嵌套 import Point

運行看看效果:
在這裏插入圖片描述
嵌套.py模塊導入了,但是test.py模塊導入失敗,雖然沒有報錯,但是沒有輸出successfully import!字樣,爲了證明導入失敗,我們再在test.py模塊內寫個簡單的函數:
在這裏插入圖片描述

導入這個函數看看:

import os
import sys
sys.path.append(os.pardir)
# path = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# sys.path.insert(0, path)
from test import fun
from classfile.嵌套 import Point

看看結果:
在這裏插入圖片描述

失敗了。
總結一下,第一種方法功能最全,可以導入test.py和嵌套.py;第二種方法可以導入嵌套.py但是不能導入test.py

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章