[英]Minesweeper: Python error. AttributeError: type object has no attribute
I am quite new to coding and is having trouble with accessing the attributes of objects inside of another object.我对编码很陌生,并且在访问另一个对象内部的对象属性时遇到了麻烦。 I have tried explicitly creating a method for returning the attribut to no awail.
我已经尝试明确创建一个方法来返回属性,但不要等待。 i cant seem to find a good explination online.
我似乎无法在网上找到一个好的解释。
The code that i am working on have the ultimate goal of simulating a game of minesweeper.我正在编写的代码的最终目标是模拟扫雷游戏。 To do this i have created a class named minefield.
为此,我创建了一个名为 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)
As well as a class named Cell以及一个名为 Cell 的类
class Cell:
def __init__(self): # setup for new cell
self.revealed = False
self.bomb = False
self.flag = False
self.nearby_bombs = 0
Now, the issue that im having is that when i try to access an attribute of a cell in the minefield i get the error: AttributeError: type object 'Cell' has no attribute 'flag'现在,我遇到的问题是,当我尝试访问雷区中单元格的属性时,出现错误:AttributeError: type object 'Cell' has no attribute 'flag'
The code that im trying to run right now (resulting in the error) using theese classes is quite simple (see below) but i will need to use these attributes for many planned functions later in the program.我现在尝试使用这些类运行的代码(导致错误)非常简单(见下文),但我将需要在程序稍后的许多计划功能中使用这些属性。
my_minefield = Minefield(5, 5, 2)
if my_minefield.minefield[1][1].flag:
print ("yay")
I am not sure why this isnt working and would greatly appreciate any help in understanding the issue.我不确定为什么这不起作用,并且非常感谢任何有助于理解该问题的帮助。 Thanks!
谢谢!
Here:这里:
self.minefield[x].append(Cell)
You're appending the Cell
class, not an instance of it.您正在附加
Cell
类,而不是它的实例。 You have to instanciate the class by calling it:您必须通过调用它来实例化该类:
self.minefield[x].append(Cell())
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.