英文:
Python Attribute Error 'Map' object has no attribute 'cells'
问题
以下是您要求的翻译部分:
我试图将 Java 代码翻译成 Python,但是遇到了一个找不到属性的错误。
这是可正常工作的 Java 代码:
Map.java
public class Map {
private Cell[][] cells;
public Map() {
this.cells = new Cell[7][7];
for (int i = 0; i < 7; i++) {
for (int j = 0; j < 7; j++) {
this.cells[i][j] = new Cell();
}
}
}
}
Cell.java
public class Cell {
private Object occupiedObject;
public Cell() {
this.occupiedObject = null;
}
}
这是我遇到错误的 Python 代码:
Map.py
from Cell import Cell
class Map():
def __init__(self):
for i in range(7):
for j in range(7):
self.cells[i][j] = Cell()
Cell.py
class Cell():
def __init__(self):
self.occupiedObject = None
注意:由于 Python 中的列表(list)和 Java 中的数组(array)有些不同,需要正确地初始化 self.cells
列表,以避免出现属性错误。
英文:
I'm trying to translate a java code into Python, but I'm encountering an attribute not found error.
Here's the java code that works:
Map.java
public class Map {
private Cell[][] cells;
public Map() {
this.cells = new Cell[7][7];
for (int i = 0; i < 7; i++) {
for (int j = 0; j < 7; j++) {
this.cells[i][j] = new Cell();
}
}
}
}
Cell.java
public class Cell {
private Object occupiedObject;
public Cell() {
this.occupiedObject = null;
}
}
Here's my Python code that has the error:
Map.py
from Cell import Cell
class Map():
def __init__(self):
for i in range(7):
for j in range(7):
self.cells[i][j] = Cell()
Cell.py
class Cell():
def __init__(self):
self.occupiedObject = None
答案1
得分: 1
我认为你想要类似这样的内容:
class Cell:
def __init__(self):
self.occupied_object = None
class Map:
def __init__(self):
self.cells = [[Cell() for x in range(7)] for y in range(7)]
英文:
I think you want something like that:
class Cell:
def __init__(self):
self.occupied_object = None
class Map:
def __init__(self):
self.cells = [[Cell() for x in range(7)] for y in range(7)]
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论