Python中的多维数组类和线对象

Python中的多维数组类和线对象,python,object,multidimensional-array,Python,Object,Multidimensional Array,在编写自己的类来管理二维表时,我遇到了一个问题 我首先创建了一个简单的类,如下所示,创建了一个空的\u line对象,该对象根据需要复制,以创建行数: class Table(object): """Table class, allows the creation of new lines and columns to the table""" def __init__(self, col = 1, lines = 1, defaultcontent=''): self.columns

在编写自己的类来管理二维表时,我遇到了一个问题

我首先创建了一个简单的类,如下所示,创建了一个空的\u line对象,该对象根据需要复制,以创建行数:

class Table(object):
"""Table class, allows the creation of new lines and columns to the table"""
def __init__(self, col = 1, lines = 1, defaultcontent=''):
    self.columns = col
    self.lines = lines
    self.empty_line = [defaultcontent for i in range(self.columns)]
    self.table = [self.empty_line for j in range(self.lines)]

def add_line(self):
    self.table.append(self.empty_line)
    self.lines += 1

def add_column(self):
    self.empty_line.append('')
    for i in range(self.lines):
        self.table[i].append('')
然而,当我创建了一个表,例如使用
table=table(5,3)
,并使用
table.table[1][2]='something'
,我意识到
'something'
在每一行中都有自己的内容,我不能在不更改其他行的情况下更改一行。此外,
self.empty\u行
已更改

过了一会儿,我开始思考
self.empty\u行中的问题。我重写了我的类,这次去掉了
self.empty\u行
,并将其替换为原语
[''for I in range(self.columns)]
(当然也纠正了
add\u column()
方法中的错误,该方法将添加两列而不是一列!)

我的问题消失了,但一个问题仍然存在:难道
self.table=[self.empty\u line for j in range(self.lines)]
不应该为每一个新行创建一个
self.empty\u line
对象的副本,而不是以某种方式“链接”相同的
self.empty\u line
实例(这会发生变化)

那么,我做错了什么?我对python对象的了解中的漏洞在哪里?

在您的代码中:

self.empty_line = [defaultcontent for i in range(self.columns)]
self.table = [self.empty_line for j in range(self.lines)]
使用swallow copy在表的每一行中复制空的_行。您只复制了引用,而不是默认内容

要解决这个问题:

self.table = [[default_content] * self.columns for _ in range(self.lines)]
添加线也有同样的问题。 不要存储空的\u行,而是使用默认的\u内容

self.table.append([self.default_content] * self.columns)
...

请参阅:

这就是我需要绕过这个概念的地方,即浅拷贝/深拷贝差异!谢谢!