Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/290.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
python-如何不更改实例化';s属性_Python_Object_Matrix - Fatal编程技术网

python-如何不更改实例化';s属性

python-如何不更改实例化';s属性,python,object,matrix,Python,Object,Matrix,我想我有一个相当基本的问题,但我就是找不到解决办法。我的代码: class Matrix: def __init__(self,data): self.data = data def __str__(self): display = [] for row in self.data: display.append(str(row)) return '\n'.join(display) a

我想我有一个相当基本的问题,但我就是找不到解决办法。我的代码:

class Matrix:

    def __init__(self,data):
        self.data = data

    def __str__(self):
        display = []
        for row in self.data:
            display.append(str(row))
        return '\n'.join(display)


a = Matrix([[1, 2], [3, 4]])

print(a.data)

a.data = [[0,0],[0,0]]

print(a.data)

我的第一次打印工作正常:
[[1,2],[3,4]]

但是我的第二个:
[[0,0],[0,0]]

如何阻止a.data=[[0,0],[0,0]]更改属性值

所以我的第二次打印也会产生:
[[1,2],[3,4]]


我一直在寻找一个解决方案,很抱歉,如果问题已经提出,我无法找到任何解决方案。

您需要
数据
才能成为一个属性:

class Matrix:
  def __init__(self,data):
    self._data = data
  def __str__(self):
    display = []
    for row in self._data:
        display.append(str(row))
    return '\n'.join(display)
  @property
  def data(self):
      return self._data
除非添加
@setter
,否则该属性将是只读的。因此,如果您尝试将新值分配给
数据
,则会发生这种情况:

>>> a=Matrix([[1,2],[3,4]])
>>> print(a.data)
[[1, 2], [3, 4]]
>>> a.data = [[0,0],[0,0]]
Traceback (most recent call last):
  File "<pyshell#36>", line 1, in <module>
    a.data = [[0,0],[0,0]]
AttributeError: can't set attribute
>a=矩阵([[1,2],[3,4]]
>>>打印(a.数据)
[[1, 2], [3, 4]]
>>>a.data=[[0,0],[0,0]]
回溯(最近一次呼叫最后一次):
文件“”,第1行,在
a、 数据=[[0,0],[0,0]]
AttributeError:无法设置属性

如果你不想更改
a.data
的值,你为什么要做
a.data=whatever
?谷歌搜索
python\uuuu setattr\uuuuu
可能的重复你希望人们不能更改它吗?您可以将其设置为“受保护”。