因此,我正在嘗試更多地了解該__init__.py檔案的作業原理。它應該使您能夠將字典作為包匯入。我使用 VS 代碼。我test1.py按預期運行,但test2.py檔案沒有。它給了我錯誤:ModuleNotFoundError: No module named 'subdir'。test1.py我從和運行腳本test2.py。
我查找了很多資源,但我還沒有得到它太多的作業。在test2.py中,我嘗試匯入Apple類 fromclass1.py和Banana類 from class2.py(均作為包)。test2.py正在嘗試從可能導致問題的父目錄匯入,但我怎樣才能使它作業?
目錄結構
init_file_testing/
test1.py
subdir/
__init__.py
class1.py
class2.py
subdir2/
test2.py
測驗1.py
from subdir import Apple
from subdir import Banana
a = Apple("red")
print(a)
b = Banana("yellow")
print(b)
__init__.py
from subdir.test_class1 import Apple
from subdir.test_class2 import Banana
類1.py
class Apple:
def __init__(self, color):
self.color = color
def __str__(self):
return f"The color of the apple is {self.color}"
類2.py
class Banana:
def __init__(self, color):
self.color = color
def __str__(self):
return f"The color of the banana is {self.color}"
測驗2.py
import sys
sys.path.append("..")
from subdir import Apple
from subdir import Banana
a = Apple("red")
print(a)
b = Banana("yellow")
print(b)
uj5u.com熱心網友回復:
如果您運行python test1.py并且它可以作業,這意味著(除非您使用其他技術來設定sys.path)您在init_file_testing檔案夾中,并且該檔案夾位于搜索 Python 模塊的路徑上。如果你想要from subdir import一些東西,那么你需要在你的路徑上的那個檔案夾——因為那是包含subdir包的檔案夾。
如果您運行python test2.py并找到檔案,這意味著(類似的邏輯)您在subdir2. 破解路徑sys.path.append("..") 無濟于事,因為這會將subdir檔案夾放在路徑上,但您需要init_file_testing檔案夾。相對而言,即sys.path.append("../..")。
但是,如果您愿意使用相對路徑作為 hack 的一部分來完成這項作業,那么為什么不直接使用相對匯入呢?這就是您打算在包中作業的方式。
看起來像:
test1.py
from .subdir import Apple, Banana
__init__.py
from .class1 import Apple
from .class2 import Banana
test2.py
from ..subdir import Apple, Banana
然后,你只需要保證包根( init_file_testing)在模塊搜索路徑上,不管你從哪個模塊開始;并且您從根檔案夾或包檔案夾外部開始(無論如何您都應該這樣做)。確保設定路徑的一種簡單方法是在虛擬環境中安裝您的包(無論如何這是推薦的開發方法)。您也可以使用PYTHONPATH環境變數來執行此操作。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/487339.html
