简体   繁体   English

python __getitem__重载问题

[英]python __getitem__ overloading issue

I am trying to implement insert function here. 我试图在这里实现插入功能。 Well, for this class Matrix which is the child class of Grid, seem to have problem. 好吧,对于作为Grid的子类的Matrix类而言,似乎有问题。 But I don't quite understand what I am doing wrong here. 但是我不太了解我在这里做错了什么。 The error says " Grid[m][n] = value TypeError: 'type' object is not subscriptable." 错误显示为“ Grid [m] [n] =值TypeError:'type'对象不可下标。”

Please help 请帮忙

thanks 谢谢

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

here is Grid class 这是网格类

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

You're accessing the class Grid where you're looking for the object. 您正在访问要查找对象的Grid Change Grid[m][n] = value to self[m][n] = value . Grid[m][n] = value更改为self[m][n] = value

Classes can't be accessed like arrays, just objects. 类不能像数组一样被访问,只能像对象一样被访问。 Grid[m][n] = value must be replaced with self[m][n] = value , because Grid is the class, not the object, so you use self as all methods are passed the current instance as the first parameter (by the way, the word 'self' really doesn't matter, you could call it 'current_instance' or anything else if you wanted to). Grid[m][n] = value必须替换为self[m][n] = value ,因为Grid是类,而不是对象,所以您使用self,因为所有方法都将当前实例作为第一个参数传递(顺便说一句,“自我”一词真的没关系,您可以将其称为“ current_instance”或其他任意名称)。 If you wonder why it says Grid is a 'type' object, check out the first answer for this question . 如果您想知道为什么Grid是一个“类型”对象,请查看此问题的第一个答案。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM