[英]Python files needing to import components from each other
我知道另一個關於模塊相互導入的問題:(
基本上,我有一個包含以下內容的文件 main.py:
class Main :
@staticmethod
def newMouton(mouton, i, j) :
listMoutons.append(mouton)
listMoutons.append(canvas.create_image(i * coteCarre, j * coteCarre + yMargin, img = imageMouton))
@staticmethod
def delMouton(mouton) :
moutonIndex = listMoutons.index(mouton)
canvas.delete(listMoutons[moutonIndex + 1]) #en ajoutant 1, on retrouve l'obj canvas image à supprimer
listMoutons.remove(mouton)
del listMoutons[moutonIndex:(moutonIndex + 2)]
from random import randint
from simulation import Simulation
#doing some other stuff such as creating the canvas variable and creating a Simulation instance
我還有另一個文件 simulation.py :
from main import Main
class Simulation:
def __init__(self) : self._moutons = []
def moutonMort(self, mouton) :
self._moutons.remove(mouton)
pos = mouton.getPosition()
Main.delMouton(mouton)
del mouton
當我嘗試運行 main.py 時,Python 遇到了一個錯誤,它基本上說問題出在我試圖在 Main 中導入 Simulation 但隨后在 Simulation 中導入 Main 的事實。
為了更多地了解導入的工作原理,我閱讀了這個問題,但我很困惑:當我運行 main.py 時,應該會發生什么:
但事實證明並非如此:當 Python 讀取模擬文件中的 import Main 語句時,它會嘗試再次運行主文件中的內容,盡管它已經被導入
我希望我的解釋清楚
在 Simulation.py 中,您的意圖是僅通過主模塊導入 Main,而主模塊尚未准備好,因為它仍在導入模擬。 這是一個循環引用的情況。 這是開始使用 Python 時的常見問題。 您需要將模塊引用排列成樹狀結構,不應該有反向引用。
不要覺得這是一個不方便的 Pyton 約束; 它迫使您編寫好的代碼並避免您在以后遇到更多麻煩。 基本上每個類或函數都應該只關注一件事,並且應該盡量減少與其他類和函數的耦合。
看來您正在跨兩個模塊傳播問題(模擬)。 一個類的名稱 Main 不是描述性的,我不確定它代表什么。 但我建議主模塊依賴於 Simulation,Simulation 應該直接或通過 Mouton 類實現 Mouton 方法。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.