簡體   English   中英

python代碼要拆分成多個文件怎么寫?

[英]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中使用ucolorsgridentity ,因此沒有理由完全導入它們。

如果你需要導入它們,你可以從定義它們的文件中導入它們,而不是從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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM