[英]What is the most pythonic way to structure a multi-module python program?
我已經在單個文件中構建了一個相當大的程序。 該文件的大小使其無法使用,因此我決定拆分為多個模塊,但是此后一直困擾着可變范圍。 我已經對其進行了很大程度的修復(在此過程中需要大量學習),但是我渴望了解良好的結構,以避免將來通過艱辛的課程學習。 有幾點要點,但也歡迎提供一般性建議。
需要共享相同名稱空間的模塊
我有兩個似乎需要共享相同名稱空間的模塊。 一個是程序的主要流程(用於與對象之間的數據傳輸,並調用UI),另一個是UI(其響應用戶輸入,稱為主要流程)。
這些模塊中的每個模塊都應該導入另一個模塊,然后主文件同時導入兩個模塊嗎? 在我看來,這並不是特別優雅。
從[modulename]導入*
在此問題的答案中:
有建議,應避免from [modulename] import *
。
是否可以使用from [modulename] import *
來構建僅具有類定義的模塊負載? 什么是“安全”用例?
需要訪問彼此名稱空間的模塊與需要共享相同名稱空間的模塊不同。 我想不出任何東西,你可以用做from modulename import *
,你不能用做import modulename
。 您只需要在許多名稱前加上modulename.
那是好事,不是壞事。 它使您的代碼可以自我記錄,這就是為什么要避免from modulename import *
原因。
您可以使UI和主流模塊相互導入。 遇到問題的唯一方法是在函數范圍之外引用它們之間的名稱。 例如
# mainflow.py
import ui # interpreter stops reading mainflow and starts reading ui
class Foo:
...
theUI = ui.UI()
# ui.py
import mainflow # mainflow already being loaded; interpretation of ui continues uninterrupted
def dosomething():
myfoo = mainflow.Foo() # so far so good, not interpreted until the function is called
class Bar(mainflow.Foo): # mainflow.Foo not reached yet, error here
...
class UI:
...
另一方面,如果ui碰巧先被導入,那么當所有主流都已被解釋但ui僅被解釋為import mainflow
時,您將在theUI = ui.UI()
處得到錯誤。 但是,只要將所有引用相互放在函數內部,就可以相處得很好。 例如
# mainflow.py
import ui
...
theUI = None
def initialize():
global theUI
theUI = ui.UI()
類之間的依賴關系仍然存在問題。 我建議您不要那樣做。 但是,如果您這樣做了,則可以使用這種奇怪的方法使整個工作正常進行:
# mainflow.py
...
theUI = None
def initialize():
global theUI
theUI = ui.UI()
import ui # Waht!? Crazy! Import at the bottom of a file. Now all of mainflow's names are guaranteed to exist and ui can access them.
現在有了ui.py的第一個版本和mainflow.py的最后一個版本,該程序將編譯並運行。 我真的不推薦上述內容; 更好地組織您的代碼,以便您沒有此類依賴項。 但是,如果您只是在模塊中的函數之間來回調用,則不必訴諸此類技巧。
還有更多面向對象的設計方法,可以使UI和程序流不直接相互依賴,但是這樣的重新設計將涉及更多的工作,而不僅僅是將其復制和粘貼到文件中以及使用module.
作為前綴module.
除非有特定原因,否則我認為您不希望過度設計。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.