[英]python __getitem__ overloading issue
我試圖在這里實現插入功能。 好吧,對於作為Grid的子類的Matrix類而言,似乎有問題。 但是我不太了解我在這里做錯了什么。 錯誤顯示為“ Grid [m] [n] =值TypeError:'type'對象不可下標。”
請幫忙
謝謝
from Grid import Grid
class Matrix(Grid):
def __init__(self, m, n, value=None):
## super(Matrix, self).__init__(m, n)
Grid.__init__(self, m, n)
def insert(self, m, n, value=None):
Grid[m][n] = value
這是網格類
from CArray import Array
class Grid(object):
"""Represents a two-dimensional array."""
def __init__(self, rows, columns, fillValue = None):
self._data = Array(rows)
for row in xrange(rows):
self._data[row] = Array(columns, fillValue)
def getHeight(self):
"""Returns the number of rows."""
return len(self._data)
def getWidth(self):
"Returns the number of columns."""
return len(self._data[0])
def __getitem__(self, index):
"""Supports two-dimensional indexing
with [row][column]."""
return self._data[index]
def __str__(self):
"""Returns a string representation of the grid."""
result = ""
for row in xrange(self.getHeight()):
for col in xrange(self.getWidth()):
result += str(self._data[row][col]) + " "
result += "\n"
return result
您正在訪問要查找對象的Grid
類 。 將Grid[m][n] = value
更改為self[m][n] = value
。
類不能像數組一樣被訪問,只能像對象一樣被訪問。 Grid[m][n] = value
必須替換為self[m][n] = value
,因為Grid是類,而不是對象,所以您使用self,因為所有方法都將當前實例作為第一個參數傳遞(順便說一句,“自我”一詞真的沒關系,您可以將其稱為“ current_instance”或其他任意名稱)。 如果您想知道為什么Grid是一個“類型”對象,請查看此問題的第一個答案。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.