![](/img/trans.png)
[英]compilation error. AttributeError: 'module' object has no attribute 'init'
[英]Minesweeper: Python error. AttributeError: type object has no attribute
我對編碼很陌生,並且在訪問另一個對象內部的對象屬性時遇到了麻煩。 我已經嘗試明確創建一個方法來返回屬性,但不要等待。 我似乎無法在網上找到一個好的解釋。
我正在編寫的代碼的最終目標是模擬掃雷游戲。 為此,我創建了一個名為 minefield 的類。
class Minefield:
def __init__(self, height, width, bombs):
self.height = height
self.width = width
self.bombs = bombs
self.flagged_amount = 0
self.minefield = []
self.setup_minefield()
def setup_minefield(self): # setup for the minefield
for x in range(self.height):
self.minefield.append([])
for y in range(self.width):
self.minefield[x].append(Cell)
以及一個名為 Cell 的類
class Cell:
def __init__(self): # setup for new cell
self.revealed = False
self.bomb = False
self.flag = False
self.nearby_bombs = 0
現在,我遇到的問題是,當我嘗試訪問雷區中單元格的屬性時,出現錯誤:AttributeError: type object 'Cell' has no attribute 'flag'
我現在嘗試使用這些類運行的代碼(導致錯誤)非常簡單(見下文),但我將需要在程序稍后的許多計划功能中使用這些屬性。
my_minefield = Minefield(5, 5, 2)
if my_minefield.minefield[1][1].flag:
print ("yay")
我不確定為什么這不起作用,並且非常感謝任何有助於理解該問題的幫助。 謝謝!
這里:
self.minefield[x].append(Cell)
您正在附加Cell
類,而不是它的實例。 您必須通過調用它來實例化該類:
self.minefield[x].append(Cell())
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.