【问题标题】:Writing a Custom Matrix Class in Python, __setitem__ issues在 Python 中编写自定义矩阵类,__setitem__ 问题
【发布时间】:2013-04-27 03:25:42
【问题描述】:

我正在开发一个自定义类来使用 Python 处理矩阵。我遇到了一个问题,我的测试程序显然没有向我的 setitem 方法传递足够的参数。代码如下:

def __setitem__(self, rowIndex, colIndex, newVal):
    self.values[rowIndex][colIndex] = newVal

以及引发错误的测试代码:

M[0, 0] = 5.0;   M[0, 1] = 7.0;   M[0, 2] = -2.0;
M[1, 0] = 3.0;   M[1, 1] = 6.0;   M[1, 2] = 1.0;

M 在尝试设置项目之前调用 Matrix 的 init

我收到了这个错误: TypeError: setitem() 只需要 4 个参数(给定 3 个) 谢谢!

【问题讨论】:

    标签: python python-3.x


    【解决方案1】:

    错误信息说明了一切:

    TypeError: __setitem__() takes exactly 4 arguments (3 given)
    

    您的__setitem__ 需要 4(自动传递自我,一如既往):

    def __setitem__(self, rowIndex, colIndex, newVal):
    

    但是这一行:

    M[0, 0] = 5.0
    

    不会将 0、0 和 5.0 传递给__setitem__;它将 2 元组 (0, 0) 和浮点数 5.0 传递给 __setitem__。这在 Python 文档的 this section 中进行了讨论,其中调用模式为 object.__setitem__(self, key, value)

    你需要更多类似的东西

    def __setitem__(self, index, value):
        self.values[index[0]][index[1]] = value
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-01-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多