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)