Home > database >  restart the class with initial argument value python
restart the class with initial argument value python

Time:10-17

I am trying to do a class to manipulate a nested list ,

a_list = [ a, b, c, d, e, f, g] will be an initial argument , then I will have some other methods to manipulate the list. However, I will need to keep a copy of the original list, that by anytime I can restart it to the initial stage by calling the restart() method ,

i tried a couple of times but it didn't work, can anyone give me a hand?

class Sample:
    def __init__(self, a_list, count):
        self.__a_list = a_list
        self.__count = 0 
        self.__reset_list = a_list.copy()  

    def restart(self):
        self.__a_list = self.__reset_list
        return

This is a full test case, it did not get back to the original value:

class Sample:
    def __init__(self, a_list, count=0):
        self.__a_list = a_list
        self.__count = 0 
        self.__reset_list = a_list.copy()  
    
    def set_update(self):
        self.__a_list[2][2] = "S"

    def restart(self):
        self.__a_list = self.__reset_list
        return

    def __str__(self):
        result_list = self.__a_list
        result = ''
        for i in range(len(result_list)):
            for j in range(len(result_list[i])):
                result  = result_list[i][j]   ' '
            if i < len(result_list) -1: 
                result  = '\n'
        return result

    


test = [
    ['*', '*', '*', '*', '*', '*', '*', '*'],
    ['*', ' ', ' ', ' ', ' ', ' ', ' ', ' '],
    ['*', ' ', ' ', '#', 'P', ' ', ' ', '*'],
    ['*', '*', '*', '*', '*', ' ', '#', '*'],
    ['*', 'o', ' ', ' ', ' ', ' ', ' ', '*'],
    ['*', ' ', ' ', ' ', ' ', ' ', 'o', '*'],
    ['*', '*', '*', ' ', '*', '*', '*', '*']
]


a_case =   Sample(test)

print(a_case)

a_case.set_update()

print(a_case)

a_case.restart()

print(a_case)

CodePudding user response:

You need to copy the list on restart:

def restart(self):
    self.__a_list = self.__reset_list.copy()

Otherwise __a_list points to the same list as __reset_list, and the latter will reflect any modifications made to __a_list

CodePudding user response:

One thing i noticed was, this issue is not happening in 1D array. as a solution you can use deepcopy. check the answer below.

import copy
class Sample:
    def __init__(self, a_list, count=0):
        self.__a_list = a_list
        self.__count = 0 
        self.__reset_list = copy.deepcopy(a_list) #use deepcopy to copy the array
  • Related