我正在开发一个自定义类来使用 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__() takes exactly 4 arguments (3 given)
最佳答案
错误信息说明了一切:
TypeError: __setitem__() takes exactly 4 arguments (3 given)
你的 __setitem__
需要 4(self 被自动传递,像往常一样):
def __setitem__(self, rowIndex, colIndex, newVal):
但是这一行:
M[0, 0] = 5.0
不将 0、0 和 5.0 传递给 __setitem__
;它将二元组 (0, 0)
和 float 5.0
传递给 __setitem__
。这在 this section 中讨论Python 文档,其中调用模式是 object.__setitem__(self, key, value)
。
你需要更多类似的东西
def __setitem__(self, index, value):
self.values[index[0]][index[1]] = value
关于python - 在 Python 中编写自定义矩阵类,__setitem__ 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16248012/