I am currently working on this code for my homework assignment involving Matrix Implementation:
class MyMatrix(object):
def __init__(self, n, m, t):
self.n = n
self.m = m
self.t = t
self.data = []
for i in range(0, self.n):
row = []
for i in range (0, self.m):
row.append(self.t())
self.data.append(row)
def set(self, i, j, v):
self.data[i][j] = v
def get(self, i, j):
self.data[i][j]
def __str__(self):
n = self.__class__.__name__ + "({})".format((self.n,self.m))
for i in range(0, self.n):
for j in range(0, self.m):
s += str(self.get(i,j)) + " "
s += "\n"
return s
class MySparseMatrix(MyMatrix):
def __init__(self, n, m, t):
self.n = n
self.m = m
self.t = t
self.data = {}
def set(self, i, j, v):
key = (i, j)
self.data[key] = v
def get(self, i,j):
key = (i, j)
return self.data.get(key, self.t())
我正在尝试打印:
tt = MySparseMatrix(int, 2, 2)
tt.set(0,0,11)
tt.set(0,1,5)
tt.set(1,0,2)
print(tt.get(0,1))
print("tt = ", tt)
但它给了我
TypeError: 'int' object is not callable
有关如何解决此错误的任何建议?我是Python的新手。
答案 0 :(得分:2)
您正在调用self.t()
这是一个整数tt = MySparseMatrix(int, 2, 2)
。将整数值2传递给实例变量t
。为变量找一个有意义的名称可以帮助你避免这种错误。
示例:
>>> a = 1
>>> a()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'int' object is not callable
答案 1 :(得分:1)
最后一个返回行self.t()
有问题删除paranthas。
t是一个整数,您正在尝试执行导致错误的方法调用。