Python属性错误 ‘Map’对象没有属性’cells’。

huangapple go评论74阅读模式
英文:

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 &lt; 7; i++) {
      for (int j = 0; j &lt; 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)]

huangapple
  • 本文由 发表于 2020年3月15日 09:33:55
  • 转载请务必保留本文链接:https://go.coder-hub.com/60688936.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定