两个对象共享相同的列表

时间:2016-11-14 15:42:45

标签: python python-2.7

CODE:

    class matrix():

    row=0
    colum=0
    def __init__(self,x,y):
    self.m=[]
        self.row=x
        self.colum=y
        #Makes a empty matrix of size x*y
        for i in range(self.row):
            self.m.append([])
            for j in range(self.colum):
                self.m[i].append(int(raw_input("Enter element")))
#To diplay the matrix
def display(x):
    k=x.m
    for i in range(0,x.row):
            for j in range(0,x.colum):
                k[i][j]=x.m[i][j]
    return k
row1=int(raw_input("Enter Number of rows of 1st Matrix"))
colum1=int(raw_input("Enter Number of colume of 1st Martrix"))
matrix1=matrix(row1,colum1)
print "1st Matrix:",display(matrix1) # displaying the first matix before adding elements
row2=int(raw_input("Enter Number of rows of 2nd Matrix"))
colum2=int(raw_input("Enter Number of colume of 2nd Martrix"))
matrix2=matrix(row2,colum2)
print "Matrix 2:",display(matrix2) #displaying the second matrix before adding elements

输出:

Enter Number of rows of 1st Matrix2
Enter Number of colume of 1st Martrix2
Enter element11
Enter element22
Enter element33
Enter element44
1st Matrix: [[11, 22], [33, 44]]
Enter Number of rows of 2nd Matrix2
Enter Number of colume of 2nd Martrix3
Enter element1
Enter element2
Enter element3
Enter element4
Enter element5
Enter element6
Matrix 2: [[11, 22, 1, 2, 3], [33, 44, 4, 5, 6], [], []]

我在python 2.7中编写了以下代码,我期望发生的是使用类矩阵的构造函数创建两个给定大小的matix。 如输出中所示,对象即矩阵1和矩阵2共享相同的列表m。我们默认情况下不应该存储两个单独列表。 预期矩阵2是

[[1,2,3],[4,5,6]]

1 个答案:

答案 0 :(得分:1)

您可以将def display函数移动到类本身中。这将成为您从matrix对象调用的方法,即matrix1.display()。变量mrowcolumn当前未保存在matrix对象中。请尝试下面的代码。

class matrix(object):
    def __init__(self,x,y):
        self.m = []
        self.row = x
        self.colum = y
        #Makes a empty matrix of size x*y
        for i in range(self.row):
            self.m.append([])
            for j in range(self.colum):
                self.m[i].append(int(raw_input("Enter element ({},{}): ".format(i,j))))

    #To diplay the matrix
    def display(self):
        for r in self.m:
            print(r)


>>> matrix1 = matrix(2,2)
Enter element (0, 0): 11
Enter element (0, 1): 22
Enter element (1, 0): 33
Enter element (1, 1): 44

>>> matrix1.display()
[11, 22]
[33, 44]