[英]How to write python code to be split into multiple files?
目前我有一個 python 文件,它是這樣的(非常簡化):
u = 30
colors = ('blue', 'red')
grid = [0, 1]
class entity:
def __init___(self, x, color)
self.x = x
self.color = color
def move(self):
print(grid[self.x + 1], self.color)
foo = entity(0, 'blue')
bar = entity(0, 'red')
while true:
foo.move()
bar.move()
我試着把它分開,我得到了這個:
# initialisation.py
u = 30
colors = ('blue', 'red')
# grid_map.py
from initialisation import u, colors
grid = [0, 1]
# classes.py
from map import u, colors, grid # or *
class entity:
def __init___(self, x, color)
self.x = x
self.color = color
def move(self):
print(grid[self.x + 1], self.color)
# objects.py
from classes import u, colors, grid, entity # or *
foo = entity(0, 'blue')
bar = entity(0, 'red')
# main.py
from objects import u, colors, grid, entity, foo, bar # or *
while true:
foo.move()
bar.move()
現在,我覺得我應該以一種不是從一個文件到下一個文件的導入鏈的方式導入,但我不確定具體如何導入。
(希望這是一個最小的、可重現的例子)
作為鏈導入是沒有用的,除了非常具體的實例,其中模塊在導入的 object 或 class 上添加或定義功能。由於您沒有在main.py
中使用u
、 colors
、 grid
或entity
,因此沒有理由完全導入它們。
如果你需要導入它們,你可以從定義它們的文件中導入它們,而不是從objects
中導入。
在objects.py
中,您只需要從classes
中導入entity
,而在classes
中,您只需要從map
中導入網grid
(順便說一句, map
是一個錯誤的名稱,因為它隱藏了內部map
函數)。
無需導入您不使用的符號——您不必考慮要導入的模塊需要什么; 該模塊自己負責。
(另一個小挑剔;class 名稱應該有 TitleCase,因此Entity
將是正確的大寫(我還建議更好的 class 名稱,因為Entity
並沒有說太多))(它是True
,不是true
)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.