0

My python code is composed of two classes. One attribute in one of the classes is a list where the elements of the list are instances of the other class. A block_wr method update one of the element in the list but even if I specified the index I want to update my method update all the element in the list. You can see in my code that I try to write in the element number 0 of the list but when I print both the element 0 and the element 1 have been changed. I have found a solution (the comment in the data_wr method) but I really do not understand why the behavior change when I use the other implementation for the update. Here is the code:

class block:
    def __init__(self, data = bytearray(512)):
        self.data = data
    def data_rd(self):
        return self.data
    def data_wr(self, data : bytearray):
        self.data[:len(data)] = data
        # use instead self.data = data , but why???
        self.data[len(data):] = [0 for i in range(512 - len(data))]

class file_tbl:
    def __init__(self):
        self.blocks_number = 480
        self.blocks = [block() for i in range(self.blocks_number)]
    def blocks_rd(self, number : int):
        return self.blocks[number]
    def blocks_wr(self, number : int, data : bytearray):
        self.blocks[number].data_wr(data)

if __name__=="__main__":
    
    file_tblx = file_tbl()
    
    data = bytearray(b'')
    for i in range(256):
        data.append(i)

    file_tblx.blocks_wr(0, data)
    print(file_tblx.blocks_rd(0).data_rd())
    print(file_tblx.blocks_rd(1).data_rd())

Thanks in advance for the answers and I apologize if it is a naive question (I'm kinda new to programming)

tomtom
  • 1
  • 1
  • All your blocks have the same `data` attribute because you're using the default. – Barmar Jul 23 '21 at 16:36
  • @Barmar thanks for the reply. I have read the question about defaults argument but there is still a point where I need clarification. When I use `self.data[:len(data)] = data` the default changes for all the blocks but why the same thing does not happen if I use `self.data = data`? I would imagine the same behavior but they differ. Why? – tomtom Jul 24 '21 at 05:32
  • Because the first modifies the list in place, the second creates a new list and assigns it to the instance attribute. It's the same as when you do `a = [1, 2, 3]; b = a` then either `a[:] = [4, 5]` or `a = [4, 5]`. The first will affect `b`, the second doesn't. – Barmar Jul 24 '21 at 16:54

0 Answers0