[英]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.