我不太了解python的继承方法。我有一个这样的类,它处理一个特殊的矩阵。
class PSSM:
matrix = {}
matrixfile = ""
def __init__(self,matrixfile):
self.matrixfile = matrixfile
PSSM.matrix = {}
PSSM.matrixfile = matrixfile
try:
f = open("%s" %matrixfile,"r")
for i in f:
PSSM.matrix[i.split()[0]] = []
for j in i.split():
try:
PSSM.matrix[i.split()[0]].append(float(j))
except ValueError:
continue
f.close()
except IOError:
try:
for i in StringIO(matrixfile):
PSSM.matrix[i.split()[0]] = []
for j in i.split():
try:
PSSM.matrix[i.split()[0]].append(float(j))
except ValueError:
continue
except ValueError:
return
def normalize(self):
newmatrix = self.matrix
for i in range(len(newmatrix["A"])):
suma = 0
for j in newmatrix.keys():
suma += newmatrix[j][i]
for j in newmatrix.keys():
newmatrix[j][i] = newmatrix[j][i]/suma
results = ""
for i in newmatrix.keys():
results += i
for j in newmatrix[i]:
results += "\t% 6.2f" %j
results += "\n"
return results
程序运行正常,但是当我尝试打印并测试它时,我遇到了一些意想不到的结果。
我也有一个printmatrix
对象,它打印矩阵(将其添加到字符串中并返回字符串)。
#returns the matrix I used as input
print PSSM.printmatrix(a)
# returns the normalized matrix as expected
print PSSM.normalize(a)
但如果我跑
print PSSM.printmatrix(a)
再次返回规范化矩阵。
类中的matrix
变量以某种方式继承newmatrix
变量?
如果我没有在任何地方改变它,matrix
怎么可能发生变化?
我只是从中复制了值,并且只更改了newmatrix
变量。
答案 0 :(得分:2)
class PSSM:
matrix = {}
matrixfile = ""
Matrix和matrixfile不是绑定到实例,而是绑定到类本身。所以该类的所有实例都共享它。
将它们移到__init__
函数:
def __init__(self,matrixfile):
self.matrix = {}
self.matrixfile = matrixfile
同样适用于PSSM.matrix
,将其更改为self.matrix
同样使用OO,你应该创建一个PSSM实例并使用它。
myMatrixFile = "bla"
myPssm = PSSM(myMatrixFile)
print myPssm.printmatrix() #returns the matrix I used as input
print myPssm.normalize() # returns the normalized matrix as expected