0

I have a pretty basic problem I guess, but I just can't get to the solution. My Code:

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)

my first print works as intended: [[1,2],[3,4]]
but my second: [[0,0],[0,0]]

How can I stop my attribute value being changed by a.data = [[0,0],[0,0]]?

So that my second print also yields: [[1,2],[3,4]]?

I was looking for a solution pretty long, sorry if the question is already asked, I wasn't able to find any solution.

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
BrainBug
  • 3
  • 3

1 Answers1

0

You need data to be a property:

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

Unless you add a @setter the property will be read-only. So then this will happen if you try to assign a new value to data:

>>> 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
BoarGules
  • 16,440
  • 2
  • 27
  • 44